from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from random import randint, shuffle
from django.utils import timezone
import requests, json, time, jwt, datetime, random, re, base64, calendar, pymysql
from django.conf import settings
from rest_framework.viewsets import ModelViewSet
from django.db.models import Q, F
from decimal import Decimal
from django.db.models import Count, Sum, Max, Min, Avg
from rest_framework import filters
from django_filters.rest_framework import DjangoFilterBackend
from django.shortcuts import render
from django.db.models.expressions import RawSQL
from django.db import transaction
from django_redis import get_redis_connection

from businesses.serializers import *
from equity_mall.utils.WXBizDataCrypt import WXBizDataCrypt
from equity_mall.utils.utils import bind_customer, random_str, mmpaymkttransfers, get_sign_HMACSHA1, redis_baidu_token, ryx_profitsharing_order
from activities.models import Channel
from customers.utils import pay_transactions_jsapi, AlipayOpen, favor_distributed_coupons, favor_query_coupons, pay_transactions_native, cmf_pay_transactions_jsapi, favor_query_coupons_sichun, favor_distributed_coupons_sichun
from managers.tasks import capture_payeeFullName
from equity_mall.utils.pages import MyPage, ElectLikePage
from businesses.filters import *
from businesses.utils import create_inviter_qrcode
from equity_mall.utils.qiniu_storage import pic_upload
from businesses.tasks import mobile_bank_vouchers_update, cancel_over_time_order
from equity_mall.utils.wash_level1 import get_user_by_code
from equity_mall.utils.common_msg import common_msg
from equity_mall.utils.utils import get_sign
from orders.tasks import add_orderinfo_index


class AliDiscountCouponModelViewSet(ModelViewSet):

    pagination_class = MyPage

    def get_queryset(self):
        merchant_id = self.request.query_params.get('merchant_id', None)
        queryset = AliDiscountCoupon.objects.filter(coupon_status=1)
        if self.action == 'limit_alidiscountcoupon':
            queryset = queryset.filter(coupon_way=3, publish_end_time__gte=datetime.datetime.now()).order_by('start_enable_time')
            return queryset
        elif self.action == 'list':
            queryset = queryset.filter(coupon_way=2)
            if merchant_id:
                queryset = queryset.filter(alidiscountcouponmerchant__merchant_id=merchant_id, remain_number__gt=0, publish_end_time__gte=datetime.datetime.now())
            else:
                queryset = queryset.filter(is_union=1, publish_end_time__gte=datetime.datetime.now())
        else:
            queryset = queryset.filter(coupon_way__in=[2, 3])
        return queryset.order_by('-id')

    def get_serializer_class(self):
        return AliDiscountCouponModelSerializer

    def get_serializer_context(self):
        user = self.request.iser
        return {'user': user}

    def retrieve(self, request, *args, **kwargs):
        activity = self.get_object()
        user = self.request.iser
        today = datetime.datetime.now()
        out_biz_no = f'{str(today).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}'
        try:
            channelcommonvoucher = activity.alidiscountcouponchannelcommonvoucher
            if channelcommonvoucher.distributed_limit_by_time == 1:
                week = str(today.weekday())
                enable_time = datetime.datetime.now().strftime('1970-01-01 %H:%M:%S')
                alidiscountcoupondstributedlimit = AliDiscountCouponDistributedLimit.objects.filter(ali_discount_coupon_common_voucher_id=channelcommonvoucher.id, weeks__contains=week, start_enable_time__lte=enable_time, end_enable_time__gte=enable_time)
                if not alidiscountcoupondstributedlimit:
                    return Response({'error': '没到活动派发时间'}, status=status.HTTP_400_BAD_REQUEST)
            if channelcommonvoucher.join_limit_by_bay == 1:
                begin_time = today.strftime('%Y-%m-%d 00:00:00')
                end_time = today.strftime('%Y-%m-%d 23:59:59')
                max_no = AliDiscountCouponInfo.objects.filter(alidiscountcoupon_id=activity.id, gmt_create__gte=begin_time, gmt_create__lte=end_time, customeruservice_id=user.id).count()
                if max_no >= channelcommonvoucher.join_limit_by_bay_count:
                    return Response({'error': '今天的优惠券已领取完毕，请明天0点继续参与，感谢您对本活动的支持！'}, status=status.HTTP_400_BAD_REQUEST)
            elif channelcommonvoucher.join_limit_by_bay == 2:
                begin_time = today.strftime('%Y-%m-01 00:00:00')
                _, last_day = calendar.monthrange(today.year, today.month)
                end_time = datetime.datetime(today.year, today.month, last_day).strftime('%Y-%m-%d 23:59:59')
                max_no = AliDiscountCouponInfo.objects.filter(alidiscountcoupon_id=activity.id, gmt_create__gte=begin_time, gmt_create__lte=end_time, customeruservice_id=user.id).count()
                if max_no >= channelcommonvoucher.join_limit_by_bay_count:
                    return Response({'error': '本月的优惠券已领取完毕，请下个月继续参与，感谢您对本活动的支持！'}, status=status.HTTP_400_BAD_REQUEST)
            elif channelcommonvoucher.join_limit_by_bay == 4:
                begin_time = today - datetime.timedelta(days=today.weekday())
                end_time = (begin_time + datetime.timedelta(days=6)).strftime('%Y-%m-%d 23:59:59')
                begin_time = begin_time.strftime('%Y-%m-01 00:00:00')
                max_no = AliDiscountCouponInfo.objects.filter(alidiscountcoupon_id=activity.id, gmt_create__gte=begin_time, gmt_create__lte=end_time, customeruservice_id=user.id).count()
                if max_no >= channelcommonvoucher.join_limit_by_bay_count:
                    return Response({'error': '本周的优惠券已领取完毕，请下礼拜继续参与，感谢您对本活动的支持！'}, status=status.HTTP_400_BAD_REQUEST)
        except:
            pass
        if activity.is_white:
            is_white = AliDiscountCouponWhiteTable.objects.filter(mobile=user.mobile, alidiscountcoupon_id=activity.id)
            if not is_white:
                return Response({'error': '您没有该优惠券领取权限，请联系客户经理参与活动。'}, status=status.HTTP_400_BAD_REQUEST)
        if activity.max_number_by_day:
            begin_time = datetime.datetime.now().strftime('%Y-%m-%d 00:00:00')
            end_time = datetime.datetime.now().strftime('%Y-%m-%d 23:59:59')
            max_no = AliDiscountCouponInfo.objects.filter(alidiscountcoupon_id=activity.id, gmt_create__gte=begin_time, gmt_create__lte=end_time).count()
            if max_no >= activity.max_number_by_day:
                return Response({'error': '今天的优惠券已领取完毕，请明天0点继续参与，感谢您对本活动的支持！'}, status=status.HTTP_400_BAD_REQUEST)
        if activity.max_number_by_user:
            max_no = AliDiscountCouponInfo.objects.filter(alidiscountcoupon_id=activity.id, customeruservice_id=user.id).count()
            if max_no >= activity.max_number_by_user:
                return Response({'error': '用户参与活动次数已达上限，感谢您对本活动的支持！'}, status=status.HTTP_400_BAD_REQUEST)
        if activity.remain_number <= 0:
            return Response({'error': '活动已达到派发上限'}, status=status.HTTP_400_BAD_REQUEST)
        query = AliDiscountCouponInfo.objects.filter(customeruservice_id=user.id, alidiscountcoupon_id=activity.id)
        if 1 in query.values_list('status', flat=True):
            return Response({'error': '活动设定领1张使用1张规则'}, status=status.HTTP_400_BAD_REQUEST)
        elif activity.max_number_by_user <= query.count():
            return Response({'error': '活动已达到领取上限'}, status=status.HTTP_400_BAD_REQUEST)
        activity_id = activity.id
        if activity.coupon_channel == 1:
            if not user.ali_user_id:
                return Response({'error': '用户尚未关联支付宝,请使用支付宝【赋有】小程序授权登录'}, status=status.HTTP_400_BAD_REQUEST)
            alipay_obj = AlipayOpen()
            user_id = user.ali_user_id
            template_id = activity.template_id
            result = json.loads(alipay_obj.vouchersend(user_id, template_id, out_biz_no))
            if result['code'] != '10000':
                logger.error(str(result))
                try:
                    return Response({'error': result['sub_msg']}, status=status.HTTP_400_BAD_REQUEST)
                except:
                    return Response({'error': '领取失败,请联系管理员'}, status=status.HTTP_400_BAD_REQUEST)
            voucher_id = result['voucher_id']
            if activity.platform_id == 1:
                result = json.loads(alipay_obj.voucherquery(voucher_id))
                data = {
                    'alidiscountcoupon_id': activity.id,
                    'voucher_id': voucher_id,
                    'user_id': user_id,
                    'template_id': result['template_id'],
                    'gmt_active': result['gmt_active'],
                    'gmt_expired': result['gmt_expired'],
                    'total_amount': result['total_amount'],
                    'gmt_create': result['gmt_create'],
                    'available_amount': result['available_amount'],
                    'name': result['name'],
                    'out_biz_no': out_biz_no,
                    'customeruservice_id': user.id,
                    'gmt_distributed': datetime.datetime.now(),
                    'mobile': user.mobile,
                    'coupon_channel': activity.coupon_channel
                }
            else:
                gmt_create = datetime.datetime.now()
                alidiscountcouponchannelcommonvoucher = activity.alidiscountcouponchannelcommonvoucher
                if alidiscountcouponchannelcommonvoucher.usetime_type == 2:
                    gmt_expired = alidiscountcouponchannelcommonvoucher.end_fixed_time
                    gmt_active = alidiscountcouponchannelcommonvoucher.start_fixed_time
                elif alidiscountcouponchannelcommonvoucher.usetime_type == 3:
                    gmt_expired = gmt_create + datetime.timedelta(days=alidiscountcouponchannelcommonvoucher.invalid_day)
                    gmt_active = gmt_create
                else:
                    gmt_active = (gmt_create + datetime.timedelta(days=1)).strftime("%Y-%m-%d 00:00:00")
                    gmt_expired = (gmt_create + datetime.timedelta(days=alidiscountcouponchannelcommonvoucher.invalid_day)).strftime("%Y-%m-%d 23:59:59")
                data = {
                    'alidiscountcoupon_id': activity.id,
                    'voucher_id': voucher_id,
                    'user_id': user_id,
                    'template_id': activity.template_id,
                    'gmt_active': gmt_active,
                    'gmt_expired': gmt_expired,
                    'total_amount': activity.amount,
                    'gmt_create': gmt_create,
                    'available_amount': activity.amount,
                    'name': activity.activity_name,
                    'out_biz_no': out_biz_no,
                    'customeruservice_id': user.id,
                    'gmt_distributed': datetime.datetime.now(),
                    'mobile': user.mobile,
                    'coupon_channel': activity.coupon_channel
                }
            voucherinfo, create = AliDiscountCouponInfo.objects.get_or_create(defaults=data, voucher_id=voucher_id)
            while True:
                activity = AliDiscountCoupon.objects.get(id=activity_id)
                activity_origin_send_count = activity.send_count
                activity_origin_remain_number = activity.remain_number
                activity_new_send_count = activity_origin_send_count + 1
                activity_new_remain_number = activity_origin_remain_number - 1
                result = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(
                    send_count=activity_new_send_count,
                    remain_number=activity_new_remain_number
                )
                if result == 0:
                    continue
                break
            if create:
                return Response({'success': '领取成功', 'coupon_id': voucherinfo.id}, status=status.HTTP_200_OK)
            else:
                return Response({'error': '已经领取过了'}, status=status.HTTP_400_BAD_REQUEST)
        elif activity.coupon_channel == 2:
            appid = settings.CUSTOMER_APP_ID_WYH
            openid = user.wyh_openid
            if activity.platform_id == 13:
                distribute_channel = Channel.objects.get(id=13)
            else:
                distribute_channel = Channel.objects.get(id=9)
            data_json = {
                "stock_id": activity.template_id,
                "out_request_no": out_biz_no,
                "appid": appid,
                "stock_creator_mchid": activity.platform.mchid
            }
            data_dict = favor_distributed_coupons_sichun(data_json, openid, distribute_channel)
            if 'code' in data_dict:
                return Response({'error': data_dict['message']}, status=status.HTTP_400_BAD_REQUEST)
            coupon_id = data_dict['coupon_id']
            voucherinfo = AliDiscountCouponInfo.objects.filter(voucher_id=coupon_id).first()
            if voucherinfo:
                return Response({'error': '已经领取过了'}, status=status.HTTP_400_BAD_REQUEST)
            result = favor_query_coupons_sichun(coupon_id, openid, appid, distribute_channel)
            data = {
                'alidiscountcoupon_id': activity.id,
                'voucher_id': coupon_id,
                'user_id': openid,
                'template_id': result['stock_id'],
                'gmt_active': result['available_begin_time'].replace('T', ' ').replace('+08:00', ''),
                'gmt_expired': result['available_end_time'].replace('T', ' ').replace('+08:00', ''),
                'total_amount': result['normal_coupon_information']['coupon_amount'] / 100,
                'gmt_create': datetime.datetime.now(),
                'available_amount': result['normal_coupon_information']['coupon_amount'] / 100,
                'name': result['coupon_name'],
                'out_biz_no': out_biz_no,
                'customeruservice_id': user.id,
                'gmt_distributed': datetime.datetime.now(),
                'mobile': user.mobile,
                'coupon_channel': activity.coupon_channel
            }
            while True:
                activity = AliDiscountCoupon.objects.get(id=activity_id)
                activity_origin_send_count = activity.send_count
                activity_origin_remain_number = activity.remain_number
                activity_new_send_count = activity_origin_send_count + 1
                activity_new_remain_number = activity_origin_remain_number - 1
                result = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(
                    send_count=activity_new_send_count,
                    remain_number=activity_new_remain_number
                )
                if result == 0:
                    continue
                break
            voucherinfo, create = AliDiscountCouponInfo.objects.get_or_create(defaults=data, voucher_id=coupon_id)
            if create:
                return Response({'success': '领取成功', 'coupon_id': voucherinfo.id}, status=status.HTTP_200_OK)
            else:
                return Response({'error': '已经领取过了'}, status=status.HTTP_400_BAD_REQUEST)
        else:
            voucher_id = f'{datetime.datetime.now().strftime("%Y%m%d%H%M%S")}{random_str(14)}'
            user_id = user.ali_user_id
            gmt_create = datetime.datetime.now()
            alidiscountcouponchannelcommonvoucher = activity.alidiscountcouponchannelcommonvoucher
            if alidiscountcouponchannelcommonvoucher.usetime_type == 2:
                gmt_expired = alidiscountcouponchannelcommonvoucher.end_fixed_time
                gmt_active = alidiscountcouponchannelcommonvoucher.start_fixed_time
            elif alidiscountcouponchannelcommonvoucher.usetime_type == 3:
                gmt_expired = gmt_create + datetime.timedelta(days=alidiscountcouponchannelcommonvoucher.invalid_day)
                gmt_active = gmt_create
            else:
                gmt_active = (gmt_create + datetime.timedelta(days=1)).strftime("%Y-%m-%d 00:00:00")
                gmt_expired = (gmt_create + datetime.timedelta(
                    days=alidiscountcouponchannelcommonvoucher.invalid_day)).strftime("%Y-%m-%d 23:59:59")
            data = {
                'alidiscountcoupon_id': activity.id,
                'voucher_id': voucher_id,
                'user_id': user_id,
                'template_id': activity.template_id,
                'gmt_active': gmt_active,
                'gmt_expired': gmt_expired,
                'total_amount': activity.amount,
                'gmt_create': gmt_create,
                'available_amount': activity.amount,
                'name': activity.activity_name,
                'out_biz_no': out_biz_no,
                'customeruservice_id': user.id,
                'mobile': user.mobile,
                'gmt_distributed': datetime.datetime.now(),
                'coupon_channel': activity.coupon_channel
            }
            while True:
                activity = AliDiscountCoupon.objects.get(id=activity_id)
                activity_origin_send_count = activity.send_count
                activity_origin_remain_number = activity.remain_number
                activity_new_send_count = activity_origin_send_count + 1
                activity_new_remain_number = activity_origin_remain_number - 1
                result = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(
                    send_count=activity_new_send_count,
                    remain_number=activity_new_remain_number
                )
                if result == 0:
                    continue
                break
            voucherinfo, create = AliDiscountCouponInfo.objects.get_or_create(defaults=data, voucher_id=voucher_id)
            if create:
                return Response({'success': '领取成功', 'coupon_id': voucherinfo.id}, status=status.HTTP_200_OK)
            else:
                return Response({'error': '已经领取过了'}, status=status.HTTP_400_BAD_REQUEST)

    def allow_coupon_wyh(self, request):
        user = self.request.iser
        identify = self.request.query_params.get('identify', None)
        longitude = self.request.query_params.get('longitude', None)
        latitude = self.request.query_params.get('latitude', None)
        if not all([identify]):
            return Response({'error': '缺少必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            activity = AliDiscountCoupon.objects.get(template_id=identify, coupon_way=8)
        except:
            return Response({'error': '无效活动参数,请联系管理员'}, status=status.HTTP_400_BAD_REQUEST)
        data = {}
        data['activity_name'] = activity.activity_name
        if activity.coupon_type == 6:
            data['amount'] = '商品兑换券'
        else:
            data['amount'] = activity.amount
        data['floor_amount'] = activity.floor_amount
        data['publish_end_time'] = activity.publish_end_time.strftime('%Y年%m月%d日 %H:%M:%S')
        channelcommonvoucher = activity.alidiscountcouponchannelcommonvoucher
        if channelcommonvoucher.usetime_type == 2:
            data['usetime_type'] = f'固定时间段{channelcommonvoucher.start_fixed_time.strftime("%Y.%m.%d %H:%M:%S")}-{channelcommonvoucher.end_fixed_time.strftime("%Y.%m.%d %H:%M:%S")}'
        elif channelcommonvoucher.usetime_type == 3:
            data['usetime_type'] = f'领取后立即生效有效时间{channelcommonvoucher.invalid_day}天'
        else:
            data['usetime_type'] = f'领取后次日凌晨生效有效时间{channelcommonvoucher.invalid_day}天'
        if channelcommonvoucher.join_limit_by_user == 1:
            data['join_limit_by_user'] = f'活动期间每个用户可参与{channelcommonvoucher.join_limit_by_user_count}次'
        else:
            data['join_limit_by_user'] = '不限制'
        if channelcommonvoucher.join_limit_by_location == 1:
            if longitude and latitude:
                check_location = AliDiscountCouponJoinLimitLocation.objects.filter(
                    longitude_begin__lte=longitude,
                    longitude_end__gte=longitude,
                    latitude_begin__lte=latitude,
                    latitude_end__gte=latitude,
                    ali_discount_coupon_common_voucher_id=channelcommonvoucher.id
                )
                if check_location:
                    join_limit = 1
                else:
                    join_limit = 0
            else:
                join_limit = 0
            is_location = 1
        else:
            join_limit = 1
            is_location = 0
        data['activity_description'] = activity.activity_description
        if datetime.datetime.now() > activity.publish_end_time:
            a = 2
        elif datetime.datetime.now() < activity.publish_start_time:
            a = 3
        else:
            if not user:
                a = 1
            else:
                if channelcommonvoucher.join_limit_by_user == 1:
                    coupon_count = AliDiscountCouponInfo.objects.filter(alidiscountcoupon_id=activity.id, customeruservice_id=user.id).count()
                    if coupon_count >= channelcommonvoucher.join_limit_by_user_count:
                        a = 0
                    else:
                        a = 1
                else:
                    a = 1
        if activity.remain_number <= 0:
            a = 4
        data['state'] = a
        data['join_limit'] = join_limit
        data['is_location'] = is_location
        data['is_need_auth'] = activity.is_need_auth
        data['coupon_type'] = activity.coupon_type
        data['coupon_type_str'] = activity.get_coupon_type_display()
        data['coupon_channel'] = activity.coupon_channel
        data['coupon_channel_str'] = activity.get_coupon_channel_display()
        return Response(data, status=status.HTTP_200_OK)

    def retrieve_coupon_wyh(self, request):
        user = self.request.iser
        identify = self.request.data.get('identify', None)
        longitude = self.request.data.get('longitude', None)
        latitude = self.request.data.get('latitude', None)
        login_id = self.request.data.get('login_id', None)
        mobile_bank_identify = self.request.data.get('mobile_bank_identify', None)
        if not identify:
            return Response({'error': '缺少必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            activity = AliDiscountCoupon.objects.get(template_id=identify, coupon_way=8)
        except:
            return Response({'error': '无效活动参数,请联系管理员'}, status=status.HTTP_400_BAD_REQUEST)
        if activity.coupon_status != 1:
            return Response({'error': '活动已结束'}, status=status.HTTP_400_BAD_REQUEST)
        if activity.remain_number <= 0:
            return Response({'error': '活动已达到派发上限'}, status=status.HTTP_400_BAD_REQUEST)
        if activity.is_check_identity == 1:
            check_manager = User.objects.filter(mobile=user.mobile, is_active=1)
            if check_manager:
                return Response({'error': '该活动暂不允许内部员工参与，如有疑问请咨询客服。'}, status=status.HTTP_400_BAD_REQUEST)
        out_biz_no = f'{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}{"%07d" % user.id}'
        channelcommonvoucher = activity.alidiscountcouponchannelcommonvoucher
        if channelcommonvoucher.distributed_limit_by_time == 1:
            week = str(datetime.datetime.now().weekday())
            enable_time = datetime.datetime.now().strftime('1970-01-01 %H:%M:%S')
            alidiscountcoupondstributedlimit = AliDiscountCouponDistributedLimit.objects.filter(
                ali_discount_coupon_common_voucher_id=channelcommonvoucher.id, weeks__contains=week,
                start_enable_time__lte=enable_time, end_enable_time__gte=enable_time)
            if not alidiscountcoupondstributedlimit:
                return Response({'error': '没到活动派发时间'}, status=status.HTTP_400_BAD_REQUEST)
        if activity.is_white:
            is_white = AliDiscountCouponWhiteTable.objects.filter(mobile=user.mobile, alidiscountcoupon_id=activity.id)
            if not is_white:
                return Response({'error': '您没有该优惠券领取权限，请联系客户经理参与活动。'}, status=status.HTTP_400_BAD_REQUEST)
        if activity.max_number_by_day:
            begin_time = datetime.datetime.now().strftime('%Y-%m-%d 00:00:00')
            end_time = datetime.datetime.now().strftime('%Y-%m-%d 23:59:59')
            max_no = AliDiscountCouponInfo.objects.filter(alidiscountcoupon_id=activity.id,
                                                          gmt_create__gte=begin_time,
                                                          gmt_create__lte=end_time).count()
            if max_no >= activity.max_number_by_day:
                return Response({'error': '今天的优惠券已领取完毕，请明天0点继续参与，感谢您对本活动的支持！'}, status=status.HTTP_400_BAD_REQUEST)
        if channelcommonvoucher.join_limit_by_user:
            max_no = AliDiscountCouponInfo.objects.filter(alidiscountcoupon_id=activity.id, customeruservice_id=user.id).count()
            if max_no >= channelcommonvoucher.join_limit_by_user_count:
                return Response({'error': '用户参与活动次数已达上限，感谢您对本活动的支持！'}, status=status.HTTP_400_BAD_REQUEST)
        if activity.remain_number <= 0:
            return Response({'error': '活动已达到派发上限'}, status=status.HTTP_400_BAD_REQUEST)
        if user.is_auth != 2 and activity.is_need_auth == 1:
            return Response({'error': '请先完成实名认证'}, status=status.HTTP_400_BAD_REQUEST)
        if channelcommonvoucher.join_limit_by_location == 1:
            if not all([latitude, longitude]):
                return Response({'error': '请上传经纬度信息'}, status=status.HTTP_400_BAD_REQUEST)
            check_location = AliDiscountCouponJoinLimitLocation.objects.filter(
                longitude_begin__lte=longitude,
                longitude_end__gte=longitude,
                latitude_begin__lte=latitude,
                latitude_end__gte=latitude,
                ali_discount_coupon_common_voucher_id=channelcommonvoucher.id
            )
            if not check_location:
                return Response({'error': '当前区域不支持参与该活动'}, status=status.HTTP_400_BAD_REQUEST)
        activity_id = activity.id
        while True:
            activity = AliDiscountCoupon.objects.get(id=activity_id)
            activity_origin_send_count = activity.send_count
            activity_origin_remain_number = activity.remain_number
            activity_new_send_count = activity_origin_send_count + 1
            activity_new_remain_number = activity_origin_remain_number - 1
            result = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(
                send_count=activity_new_send_count,
                remain_number=activity_new_remain_number
            )
            if result == 0:
                continue
            break
        if activity.coupon_channel == 1:
            if not login_id:
                while True:
                    activity = AliDiscountCoupon.objects.get(id=activity_id)
                    activity_origin_send_count = activity.send_count
                    activity_origin_remain_number = activity.remain_number
                    activity_new_send_count = activity_origin_send_count - 1
                    activity_new_remain_number = activity_origin_remain_number + 1
                    result1 = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(
                        send_count=activity_new_send_count,
                        remain_number=activity_new_remain_number
                    )
                    if result1 == 0:
                        continue
                    break
                return Response({'error': '请上传支付宝账号'}, status=status.HTTP_400_BAD_REQUEST)
            alipay_obj = AlipayOpen()
            template_id = activity.template_id
            result = json.loads(alipay_obj.vouchersend_login_id(login_id, template_id, out_biz_no))
            if result['code'] != '10000':
                logger.error(str(result))
                while True:
                    activity = AliDiscountCoupon.objects.get(id=activity_id)
                    activity_origin_send_count = activity.send_count
                    activity_origin_remain_number = activity.remain_number
                    activity_new_send_count = activity_origin_send_count - 1
                    activity_new_remain_number = activity_origin_remain_number + 1
                    result1 = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(
                        send_count=activity_new_send_count,
                        remain_number=activity_new_remain_number
                    )
                    if result1 == 0:
                        continue
                    break
                try:
                    return Response({'error': result['sub_msg']}, status=status.HTTP_400_BAD_REQUEST)
                except:
                    return Response({'error': '领取失败,请联系管理员'}, status=status.HTTP_400_BAD_REQUEST)
            voucher_id = result['voucher_id']
            if activity.platform_id == 1:
                result = json.loads(alipay_obj.voucherquery(voucher_id))
                data = {
                    'alidiscountcoupon_id': activity.id,
                    'voucher_id': voucher_id,
                    'login_id': login_id,
                    'template_id': result['template_id'],
                    'gmt_active': result['gmt_active'],
                    'gmt_expired': result['gmt_expired'],
                    'total_amount': result['total_amount'],
                    'gmt_create': result['gmt_create'],
                    'available_amount': result['available_amount'],
                    'name': result['name'],
                    'out_biz_no': out_biz_no,
                    'customeruservice_id': user.id,
                    'gmt_distributed': datetime.datetime.now(),
                    'mobile': user.mobile,
                    'mobile_bank_identify': mobile_bank_identify,
                    'coupon_channel': activity.coupon_channel
                }
            else:
                gmt_create = datetime.datetime.now()
                alidiscountcouponchannelcommonvoucher = activity.alidiscountcouponchannelcommonvoucher
                if alidiscountcouponchannelcommonvoucher.usetime_type == 2:
                    gmt_expired = alidiscountcouponchannelcommonvoucher.end_fixed_time
                    gmt_active = alidiscountcouponchannelcommonvoucher.start_fixed_time
                elif alidiscountcouponchannelcommonvoucher.usetime_type == 3:
                    gmt_expired = gmt_create + datetime.timedelta(days=alidiscountcouponchannelcommonvoucher.invalid_day)
                    gmt_active = gmt_create
                else:
                    gmt_active = (gmt_create + datetime.timedelta(days=1)).strftime("%Y-%m-%d 00:00:00")
                    gmt_expired = (gmt_create + datetime.timedelta(days=alidiscountcouponchannelcommonvoucher.invalid_day)).strftime("%Y-%m-%d 23:59:59")
                data = {
                    'alidiscountcoupon_id': activity.id,
                    'voucher_id': voucher_id,
                    'login_id': login_id,
                    'template_id': activity.template_id,
                    'gmt_active': gmt_active,
                    'gmt_expired': gmt_expired,
                    'total_amount': activity.amount,
                    'gmt_create': gmt_create,
                    'available_amount': activity.amount,
                    'name': activity.activity_name,
                    'out_biz_no': out_biz_no,
                    'customeruservice_id': user.id,
                    'gmt_distributed': datetime.datetime.now(),
                    'mobile': user.mobile,
                    'mobile_bank_identify': mobile_bank_identify,
                    'coupon_channel': activity.coupon_channel
                }
            voucherinfo, create = AliDiscountCouponInfo.objects.get_or_create(defaults=data, voucher_id=voucher_id)
            if mobile_bank_identify and mobile_bank_identify != 'undefined':
                mobile_bank_vouchers_update.delay({"openId": mobile_bank_identify, "couponId": voucher_id, "stockId": activity.template_id, "status": "1"})
            if create:
                return Response({'success': '领取成功', 'coupon_id': voucherinfo.id}, status=status.HTTP_200_OK)
            else:
                return Response({'error': '已经领取过了'}, status=status.HTTP_400_BAD_REQUEST)
        else:
            appid = settings.CUSTOMER_APP_ID_WYH
            openid = user.wyh_openid
            if activity.platform_id == 13:
                distribute_channel = Channel.objects.get(id=13)
            else:
                distribute_channel = Channel.objects.get(id=9)
            data_json = {
                "stock_id": activity.template_id,
                "out_request_no": out_biz_no,
                "appid": appid,
                "stock_creator_mchid": activity.platform.mchid
            }
            data_dict = favor_distributed_coupons_sichun(data_json, openid, distribute_channel)
            if 'code' in data_dict:
                logger.error(str(data_dict))
                while True:
                    activity = AliDiscountCoupon.objects.get(id=activity_id)
                    activity_origin_send_count = activity.send_count
                    activity_origin_remain_number = activity.remain_number
                    activity_new_send_count = activity_origin_send_count - 1
                    activity_new_remain_number = activity_origin_remain_number + 1
                    result1 = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(
                        send_count=activity_new_send_count,
                        remain_number=activity_new_remain_number
                    )
                    if result1 == 0:
                        continue
                    break
                return Response({'error': data_dict['message']}, status=status.HTTP_400_BAD_REQUEST)
            coupon_id = data_dict['coupon_id']
            result = favor_query_coupons_sichun(coupon_id, openid, appid, distribute_channel)
            data = {
                'alidiscountcoupon_id': activity.id,
                'voucher_id': coupon_id,
                'user_id': openid,
                'appid': appid,
                'template_id': result['stock_id'],
                'gmt_active': result['available_begin_time'].replace('T', ' ').replace('+08:00', ''),
                'gmt_expired': result['available_end_time'].replace('T', ' ').replace('+08:00', ''),
                'total_amount': result['normal_coupon_information']['coupon_amount'] / 100,
                'gmt_create': datetime.datetime.now(),
                'available_amount': result['normal_coupon_information']['coupon_amount'] / 100,
                'name': result['coupon_name'],
                'out_biz_no': out_biz_no,
                'customeruservice_id': user.id,
                'gmt_distributed': datetime.datetime.now(),
                'mobile': user.mobile,
                'mobile_bank_identify': mobile_bank_identify,
                'coupon_channel': activity.coupon_channel
            }
            voucherinfo, create = AliDiscountCouponInfo.objects.get_or_create(defaults=data, voucher_id=coupon_id)
            if mobile_bank_identify and mobile_bank_identify != 'undefined':
                mobile_bank_vouchers_update.delay({"openId": mobile_bank_identify, "couponId": coupon_id, "stockId": activity.template_id, "status": "1"})
            if create:
                return Response({'success': '领取成功', 'coupon_id': voucherinfo.id}, status=status.HTTP_200_OK)
            else:
                return Response({'error': '已经领取过了'}, status=status.HTTP_400_BAD_REQUEST)

    def allow_coupon_equity(self, request):
        user = self.request.iser
        identify = self.request.query_params.get('identify', None)
        longitude = self.request.query_params.get('longitude', None)
        latitude = self.request.query_params.get('latitude', None)
        if not all([identify]):
            return Response({'error': '缺少必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        # try:
        #     activity = AliDiscountCoupon.objects.get(template_id=identify, coupon_way=8)
        # except:
        #     return Response({'error': '无效活动参数,请联系管理员'}, status=status.HTTP_400_BAD_REQUEST)

        if len(identify) == 32:
            try:
                qrcode = AliDiscountCouponQRCode.objects.get(identify=identify)
            except:
                return Response({'error': '无效二维码,请联系管理员'}, status=status.HTTP_400_BAD_REQUEST)
            activity = qrcode.alidiscountcoupon_level.activity
            if qrcode.qrcode_state == 2:
                a = 0
            else:
                a = 1
        elif len(identify) == 48:
            try:
                alidiscountcouponmanagerqrcode = AliDiscountCouponManagerQRCode.objects.get(identify=identify)
            except:
                return Response({'error': '无效二维码,请联系管理员'}, status=status.HTTP_400_BAD_REQUEST)
            activity = alidiscountcouponmanagerqrcode.alidiscountcoupon
            a = 0
        elif len(identify) == 64:
            try:
                alidiscountcoupon_level = AliDiscountCouponLevel.objects.get(identify=identify)
            except:
                return Response({'error': '无效二维码,请联系管理员'}, status=status.HTTP_400_BAD_REQUEST)
            activity = alidiscountcoupon_level.activity
            a = 1
            query = AliDiscountCouponInfo.objects.filter(alidiscountcoupon_id=activity.id, customeruservice_id=user.id)
            if 1 in query.values_list('status', flat=True):
                a = 5
            elif activity.max_number_by_user <= query.count():
                a = 0
        else:
            try:
                activity = AliDiscountCoupon.objects.get(id=identify)
            except:
                return Response({'error': '无效活动id,请联系管理员'}, status=status.HTTP_400_BAD_REQUEST)
            a = 0

        data = {}
        data['activity_name'] = activity.activity_name
        if activity.coupon_type == 6:
            data['amount'] = '商品兑换券'
        else:
            data['amount'] = activity.amount
        data['floor_amount'] = activity.floor_amount
        data['publish_end_time'] = activity.publish_end_time.strftime('%Y年%m月%d日 %H:%M:%S')
        channelcommonvoucher = activity.alidiscountcouponchannelcommonvoucher
        if channelcommonvoucher.usetime_type == 2:
            data['usetime_type'] = f'固定时间段{channelcommonvoucher.start_fixed_time.strftime("%Y.%m.%d %H:%M:%S")}-{channelcommonvoucher.end_fixed_time.strftime("%Y.%m.%d %H:%M:%S")}'
        elif channelcommonvoucher.usetime_type == 3:
            data['usetime_type'] = f'领取后立即生效有效时间{channelcommonvoucher.invalid_day}天'
        else:
            data['usetime_type'] = f'领取后次日凌晨生效有效时间{channelcommonvoucher.invalid_day}天'
        if channelcommonvoucher.join_limit_by_user == 1:
            data['join_limit_by_user'] = f'活动期间每个用户可参与{channelcommonvoucher.join_limit_by_user_count}次'
        else:
            data['join_limit_by_user'] = '不限制'
        if channelcommonvoucher.join_limit_by_location == 1:
            if longitude and latitude:
                check_location = AliDiscountCouponJoinLimitLocation.objects.filter(
                    longitude_begin__lte=longitude,
                    longitude_end__gte=longitude,
                    latitude_begin__lte=latitude,
                    latitude_end__gte=latitude,
                    ali_discount_coupon_common_voucher_id=channelcommonvoucher.id
                )
                if check_location:
                    join_limit = 1
                else:
                    join_limit = 0
            else:
                join_limit = 0
            is_location = 1
        else:
            join_limit = 1
            is_location = 0
        data['activity_description'] = activity.activity_description
        # if datetime.datetime.now() > activity.publish_end_time:
        #     a = 2
        # elif datetime.datetime.now() < activity.publish_start_time:
        #     a = 3
        # else:
        #     if not user:
        #         a = 1
        #     else:
        #         if channelcommonvoucher.join_limit_by_user == 1:
        #             coupon_count = AliDiscountCouponInfo.objects.filter(alidiscountcoupon_id=activity.id, customeruservice_id=user.id).count()
        #             if coupon_count >= channelcommonvoucher.join_limit_by_user_count:
        #                 a = 0
        #             else:
        #                 a = 1
        #         else:
        #             a = 1
        if a == 0:
            try:
                alidiscountcoupon = AliDiscountCouponInfo.objects.filter(out_biz_no=qrcode.out_biz_no).first()
                coupon_id = alidiscountcoupon.voucher_id
            except:
                alidiscountcoupon = None
                coupon_id = ''
            if alidiscountcoupon:
                if alidiscountcoupon.customeruservice_id != user.id:
                    a = 6
                    contentLink = {
                        "path": '',
                        "appid": '',
                        "is_self": ''
                    }
                else:
                    if activity.is_use_path == 1:
                        contentLink = {
                            "path": activity.use_path + f"?coupon_id={coupon_id}",
                            "appid": activity.use_appid,
                            "is_self": activity.is_self
                        }
                        a = 5
                    else:
                        contentLink = {
                            "path": '',
                            "appid": '',
                            "is_self": ''
                        }
            else:
                contentLink = {
                    "path": '',
                    "appid": '',
                    "is_self": ''
                }
        else:
            contentLink = {
                "path": '',
                "appid": '',
                "is_self": ''
            }
        if activity.remain_number <= 0:
            a = 4
        data['state'] = a
        data['join_limit'] = join_limit
        data['is_location'] = is_location
        data['is_need_auth'] = activity.is_need_auth
        data['coupon_type'] = activity.coupon_type
        data['coupon_type_str'] = activity.get_coupon_type_display()
        data['coupon_channel'] = activity.coupon_channel
        data['coupon_channel_str'] = activity.get_coupon_channel_display()
        data['contentLink'] = contentLink
        return Response(data, status=status.HTTP_200_OK)

    def retrieve_coupon_equity(self, request):
        user = self.request.iser
        identify = self.request.data.get('identify', None)
        longitude = self.request.data.get('longitude', None)
        latitude = self.request.data.get('latitude', None)
        login_id = self.request.data.get('login_id', None)
        mobile_bank_identify = self.request.data.get('mobile_bank_identify', None)
        if not identify:
            return Response({'error': '缺少必传参数', 'status': 0}, status=status.HTTP_400_BAD_REQUEST)

        if len(identify) == 32:
            try:
                qrcode = AliDiscountCouponQRCode.objects.get(identify=identify)
            except:
                return Response({'error': '无效二维码,请联系管理员', 'status': 0}, status=status.HTTP_400_BAD_REQUEST)
            if qrcode.qrcode_state == 2:
                return Response({'error': '该二维码已经被领取', 'status': 0}, status=status.HTTP_400_BAD_REQUEST)
            alidiscountcoupon_level = qrcode.alidiscountcoupon_level
            out_biz_no = qrcode.out_biz_no
            activity = alidiscountcoupon_level.activity
            if activity.is_check_identity == 1:
                check_manager = User.objects.filter(mobile=user.mobile, is_active=1)
                if check_manager:
                    return Response({'error': '该活动暂不允许内部员工参与，如有疑问请咨询客服。', 'status': 1}, status=status.HTTP_400_BAD_REQUEST)
            try:
                channelcommonvoucher = activity.alidiscountcouponchannelcommonvoucher
                if channelcommonvoucher.distributed_limit_by_time == 1:
                    week = str(datetime.datetime.now().weekday())
                    enable_time = datetime.datetime.now().strftime('1970-01-01 %H:%M:%S')
                    alidiscountcoupondstributedlimit = AliDiscountCouponDistributedLimit.objects.filter(ali_discount_coupon_common_voucher_id=channelcommonvoucher.id, weeks__contains=week, start_enable_time__lte=enable_time, end_enable_time__gte=enable_time)
                    if not alidiscountcoupondstributedlimit:
                        return Response({'error': '没到活动派发时间', 'status': 0}, status=status.HTTP_400_BAD_REQUEST)
            except:
                pass
            if activity.coupon_status != 1:
                return Response({'error': '活动已结束。', 'status': 0}, status=status.HTTP_400_BAD_REQUEST)
            if activity.is_white:
                is_white = AliDiscountCouponWhiteTable.objects.filter(mobile=user.mobile, alidiscountcoupon_id=activity.id)
                if not is_white:
                    return Response({'error': '您没有该优惠券领取权限，请联系客户经理参与活动。', 'status': 0}, status=status.HTTP_400_BAD_REQUEST)
            if user.is_auth != 2 and activity.is_need_auth == 1:
                return Response({'error': '请先完成实名认证', 'status': 0}, status=status.HTTP_400_BAD_REQUEST)
            if activity.coupon_way == 4:
                if not alidiscountcoupon_level.is_auth:
                    return Response({'error': '您无权限派发此活动', 'status': 0}, status=status.HTTP_400_BAD_REQUEST)
                if activity.remain_number <= 0:
                    return Response({'error': '活动已达到派发上限', 'status': 0}, status=status.HTTP_400_BAD_REQUEST)
            else:
                if alidiscountcoupon_level.remain_number <= 0:
                    return Response({'error': '活动已达到派发上限', 'status': 0}, status=status.HTTP_400_BAD_REQUEST)
            if activity.max_number_by_day:
                begin_time = datetime.datetime.now().strftime('%Y-%m-%d 00:00:00')
                end_time = datetime.datetime.now().strftime('%Y-%m-%d 23:59:59')
                max_no = AliDiscountCouponInfo.objects.filter(alidiscountcoupon_id=activity.id, gmt_create__gte=begin_time, gmt_create__lte=end_time).count()
                if max_no >= activity.max_number_by_day:
                    return Response({'error': '今天的优惠券已领取完毕，请明天继续参与，感谢您对本活动的支持！', 'status': 0}, status=status.HTTP_400_BAD_REQUEST)
            if activity.max_number_by_user:
                max_no = AliDiscountCouponInfo.objects.filter(alidiscountcoupon_id=activity.id, customeruservice_id=user.id).exclude(status=13).count()
                if max_no >= activity.max_number_by_user:
                    return Response({'error': '用户参与活动次数已达上限，感谢您对本活动的支持！', 'status': 0}, status=status.HTTP_400_BAD_REQUEST)
            qrcode.qrcode_state = 2
            qrcode.save()
            alidiscountcoupon_level_id = alidiscountcoupon_level.id
            activity_id = activity.id
            if activity.coupon_way == 4:
                while True:
                    activity = AliDiscountCoupon.objects.get(id=activity_id)
                    if activity.remain_number <= 0:
                        return Response({'error': '活动已达到派发上限', 'status': 0}, status=status.HTTP_400_BAD_REQUEST)
                    activity_origin_send_count = activity.send_count
                    activity_origin_remain_number = activity.remain_number
                    activity_new_send_count = activity_origin_send_count + 1
                    activity_new_remain_number = activity_origin_remain_number - 1
                    result = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(
                        send_count=activity_new_send_count,
                        remain_number=activity_new_remain_number
                    )
                    if result == 0:
                        continue
                    break
                while True:
                    alidiscountcoupon_level = AliDiscountCouponLevel.objects.get(id=alidiscountcoupon_level_id)
                    instance_origin_take_number = alidiscountcoupon_level.take_number
                    instance_origin_receive_number = alidiscountcoupon_level.receive_number
                    instance_origin_max_number = alidiscountcoupon_level.max_number
                    instance_origin_p_take_number = alidiscountcoupon_level.p_take_number
                    instance_origin_p_receive_number = alidiscountcoupon_level.p_receive_number
                    instance_origin_p_max_number = alidiscountcoupon_level.p_max_number
                    instance_new_take_number = instance_origin_take_number + 1
                    instance_new_receive_number = instance_origin_receive_number + 1
                    instance_new_max_number = instance_origin_max_number + 1
                    instance_new_p_take_number = instance_origin_p_take_number + 1
                    instance_new_p_receive_number = instance_origin_p_receive_number + 1
                    instance_new_p_max_number = instance_origin_p_max_number + 1
                    result = AliDiscountCouponLevel.objects.filter(id=alidiscountcoupon_level_id, take_number=instance_origin_take_number).update(
                        take_number=instance_new_take_number,
                        receive_number=instance_new_receive_number,
                        max_number=instance_new_max_number,
                        p_take_number=instance_new_p_take_number,
                        p_receive_number=instance_new_p_receive_number,
                        p_max_number=instance_new_p_max_number
                    )
                    if result == 0:
                        continue
                    break
                try:
                    relation_set = alidiscountcoupon_level.child_set.all()
                    for relation in relation_set:
                        parent = relation.parent
                        parent.p_take_number += 1
                        parent.p_receive_number += 1
                        parent.p_max_number += 1
                        parent.save()
                except:
                    pass
            else:
                while True:
                    alidiscountcoupon_level = AliDiscountCouponLevel.objects.get(id=alidiscountcoupon_level_id)
                    if alidiscountcoupon_level.remain_number <= 0:
                        return Response({'error': '活动已达到派发上限', 'status': 0}, status=status.HTTP_400_BAD_REQUEST)
                    instance_origin_take_number = alidiscountcoupon_level.take_number
                    instance_origin_receive_number = alidiscountcoupon_level.receive_number
                    instance_origin_remain_number = alidiscountcoupon_level.remain_number
                    instance_origin_p_take_number = alidiscountcoupon_level.p_take_number
                    instance_origin_p_receive_number = alidiscountcoupon_level.p_receive_number
                    instance_origin_p_remain_number = alidiscountcoupon_level.p_remain_number
                    instance_new_take_number = instance_origin_take_number + 1
                    instance_new_receive_number = instance_origin_receive_number + 1
                    instance_new_remain_number = instance_origin_remain_number - 1
                    instance_new_p_take_number = instance_origin_p_take_number + 1
                    instance_new_p_receive_number = instance_origin_p_receive_number + 1
                    instance_new_p_remain_number = instance_origin_p_remain_number - 1
                    result = AliDiscountCouponLevel.objects.filter(id=alidiscountcoupon_level_id, take_number=instance_origin_take_number).update(
                        take_number=instance_new_take_number,
                        receive_number=instance_new_receive_number,
                        remain_number=instance_new_remain_number,
                        p_take_number=instance_new_p_take_number,
                        p_receive_number=instance_new_p_receive_number,
                        p_remain_number=instance_new_p_remain_number
                    )
                    if result == 0:
                        continue
                    break
                while True:
                    activity = AliDiscountCoupon.objects.get(id=activity_id)
                    activity_origin_send_count = activity.send_count
                    activity_origin_remain_number = activity.remain_number
                    activity_new_send_count = activity_origin_send_count + 1
                    activity_new_remain_number = activity_origin_remain_number - 1
                    result = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(
                        send_count=activity_new_send_count,
                        remain_number=activity_new_remain_number
                    )
                    if result == 0:
                        continue
                    break
                try:
                    relation_set = alidiscountcoupon_level.child_set.all()
                    for relation in relation_set:
                        parent = relation.parent
                        parent.p_take_number += 1
                        parent.p_receive_number += 1
                        parent.p_remain_number -= 1
                        parent.save()
                except:
                    pass
            alidiscountcoupon_level_id = alidiscountcoupon_level.id
            activity_id = activity.id
            if activity.coupon_channel == 1:
                if not login_id:
                    if activity.coupon_way == 4:
                        while True:
                            activity = AliDiscountCoupon.objects.get(id=activity_id)
                            activity_origin_send_count = activity.send_count
                            activity_origin_remain_number = activity.remain_number
                            activity_new_send_count = activity_origin_send_count - 1
                            activity_new_remain_number = activity_origin_remain_number + 1
                            result1 = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(
                                send_count=activity_new_send_count,
                                remain_number=activity_new_remain_number
                            )
                            if result1 == 0:
                                continue
                            break
                        while True:
                            alidiscountcoupon_level = AliDiscountCouponLevel.objects.get(id=alidiscountcoupon_level_id)
                            instance_origin_take_number = alidiscountcoupon_level.take_number
                            instance_origin_receive_number = alidiscountcoupon_level.receive_number
                            instance_origin_max_number = alidiscountcoupon_level.max_number
                            instance_origin_p_take_number = alidiscountcoupon_level.p_take_number
                            instance_origin_p_receive_number = alidiscountcoupon_level.p_receive_number
                            instance_origin_p_max_number = alidiscountcoupon_level.p_max_number
                            instance_new_take_number = instance_origin_take_number - 1
                            instance_new_receive_number = instance_origin_receive_number - 1
                            instance_new_max_number = instance_origin_max_number - 1
                            instance_new_p_take_number = instance_origin_p_take_number + 1
                            instance_new_p_receive_number = instance_origin_p_receive_number - 1
                            instance_new_p_max_number = instance_origin_p_max_number - 1
                            result1 = AliDiscountCouponLevel.objects.filter(id=alidiscountcoupon_level_id, take_number=instance_origin_take_number).update(
                                take_number=instance_new_take_number,
                                receive_number=instance_new_receive_number,
                                max_number=instance_new_max_number,
                                p_take_number=instance_new_p_take_number,
                                p_receive_number=instance_new_p_receive_number,
                                p_max_number=instance_new_p_max_number
                            )
                            if result1 == 0:
                                continue
                            break
                        try:
                            relation_set = alidiscountcoupon_level.child_set.all()
                            for relation in relation_set:
                                parent = relation.parent
                                parent.p_take_number -= 1
                                parent.p_receive_number -= 1
                                parent.p_max_number -= 1
                                parent.save()
                        except:
                            pass
                    else:
                        while True:
                            alidiscountcoupon_level = AliDiscountCouponLevel.objects.get(id=alidiscountcoupon_level_id)
                            instance_origin_take_number = alidiscountcoupon_level.take_number
                            instance_origin_receive_number = alidiscountcoupon_level.receive_number
                            instance_origin_remain_number = alidiscountcoupon_level.remain_number
                            instance_origin_p_take_number = alidiscountcoupon_level.p_take_number
                            instance_origin_p_receive_number = alidiscountcoupon_level.p_receive_number
                            instance_origin_p_remain_number = alidiscountcoupon_level.p_remain_number
                            instance_new_take_number = instance_origin_take_number - 1
                            instance_new_receive_number = instance_origin_receive_number - 1
                            instance_new_remain_number = instance_origin_remain_number + 1
                            instance_new_p_take_number = instance_origin_p_take_number - 1
                            instance_new_p_receive_number = instance_origin_p_receive_number - 1
                            instance_new_p_remain_number = instance_origin_p_remain_number + 1
                            result1 = AliDiscountCouponLevel.objects.filter(id=alidiscountcoupon_level_id, take_number=instance_origin_take_number).update(
                                take_number=instance_new_take_number,
                                receive_number=instance_new_receive_number,
                                remain_number=instance_new_remain_number,
                                p_take_number=instance_new_p_take_number,
                                p_receive_number=instance_new_p_receive_number,
                                p_remain_number=instance_new_p_remain_number
                            )
                            if result1 == 0:
                                continue
                            break
                        while True:
                            activity = AliDiscountCoupon.objects.get(id=activity_id)
                            activity_origin_send_count = activity.send_count
                            activity_origin_remain_number = activity.remain_number
                            activity_new_send_count = activity_origin_send_count - 1
                            activity_new_remain_number = activity_origin_remain_number + 1
                            result1 = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(
                                send_count=activity_new_send_count,
                                remain_number=activity_new_remain_number
                            )
                            if result1 == 0:
                                continue
                            break
                        try:
                            relation_set = alidiscountcoupon_level.child_set.all()
                            for relation in relation_set:
                                parent = relation.parent
                                parent.p_take_number -= 1
                                parent.p_receive_number -= 1
                                parent.p_remain_number += 1
                                parent.save()
                        except:
                            pass
                    qrcode.return_msg = '请上传支付宝账号'
                    qrcode.qrcode_state = 1
                    qrcode.save()
                    return Response({'error': '请上传支付宝账号', 'status': 0}, status=status.HTTP_400_BAD_REQUEST)
                alipay_obj = AlipayOpen()
                template_id = activity.template_id
                result = json.loads(alipay_obj.vouchersend_login_id(login_id, template_id, out_biz_no))
                if result['code'] != '10000':
                    logger.error(str(result))
                    if activity.coupon_way == 4:
                        while True:
                            activity = AliDiscountCoupon.objects.get(id=activity_id)
                            activity_origin_send_count = activity.send_count
                            activity_origin_remain_number = activity.remain_number
                            activity_new_send_count = activity_origin_send_count - 1
                            activity_new_remain_number = activity_origin_remain_number + 1
                            result1 = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(
                                send_count=activity_new_send_count,
                                remain_number=activity_new_remain_number
                            )
                            if result1 == 0:
                                continue
                            break
                        while True:
                            alidiscountcoupon_level = AliDiscountCouponLevel.objects.get(id=alidiscountcoupon_level_id)
                            instance_origin_take_number = alidiscountcoupon_level.take_number
                            instance_origin_receive_number = alidiscountcoupon_level.receive_number
                            instance_origin_max_number = alidiscountcoupon_level.max_number
                            instance_origin_p_take_number = alidiscountcoupon_level.p_take_number
                            instance_origin_p_receive_number = alidiscountcoupon_level.p_receive_number
                            instance_origin_p_max_number = alidiscountcoupon_level.p_max_number
                            instance_new_take_number = instance_origin_take_number - 1
                            instance_new_receive_number = instance_origin_receive_number - 1
                            instance_new_max_number = instance_origin_max_number - 1
                            instance_new_p_take_number = instance_origin_p_take_number + 1
                            instance_new_p_receive_number = instance_origin_p_receive_number - 1
                            instance_new_p_max_number = instance_origin_p_max_number - 1
                            result1 = AliDiscountCouponLevel.objects.filter(id=alidiscountcoupon_level_id, take_number=instance_origin_take_number).update(
                                take_number=instance_new_take_number,
                                receive_number=instance_new_receive_number,
                                max_number=instance_new_max_number,
                                p_take_number=instance_new_p_take_number,
                                p_receive_number=instance_new_p_receive_number,
                                p_max_number=instance_new_p_max_number
                            )
                            if result1 == 0:
                                continue
                            break
                        try:
                            relation_set = alidiscountcoupon_level.child_set.all()
                            for relation in relation_set:
                                parent = relation.parent
                                parent.p_take_number -= 1
                                parent.p_receive_number -= 1
                                parent.p_max_number -= 1
                                parent.save()
                        except:
                            pass
                    else:
                        while True:
                            alidiscountcoupon_level = AliDiscountCouponLevel.objects.get(id=alidiscountcoupon_level_id)
                            instance_origin_take_number = alidiscountcoupon_level.take_number
                            instance_origin_receive_number = alidiscountcoupon_level.receive_number
                            instance_origin_remain_number = alidiscountcoupon_level.remain_number
                            instance_origin_p_take_number = alidiscountcoupon_level.p_take_number
                            instance_origin_p_receive_number = alidiscountcoupon_level.p_receive_number
                            instance_origin_p_remain_number = alidiscountcoupon_level.p_remain_number
                            instance_new_take_number = instance_origin_take_number - 1
                            instance_new_receive_number = instance_origin_receive_number - 1
                            instance_new_remain_number = instance_origin_remain_number + 1
                            instance_new_p_take_number = instance_origin_p_take_number - 1
                            instance_new_p_receive_number = instance_origin_p_receive_number - 1
                            instance_new_p_remain_number = instance_origin_p_remain_number + 1
                            result1 = AliDiscountCouponLevel.objects.filter(id=alidiscountcoupon_level_id, take_number=instance_origin_take_number).update(
                                take_number=instance_new_take_number,
                                receive_number=instance_new_receive_number,
                                remain_number=instance_new_remain_number,
                                p_take_number=instance_new_p_take_number,
                                p_receive_number=instance_new_p_receive_number,
                                p_remain_number=instance_new_p_remain_number
                            )
                            if result1 == 0:
                                continue
                            break
                        while True:
                            activity = AliDiscountCoupon.objects.get(id=activity_id)
                            activity_origin_send_count = activity.send_count
                            activity_origin_remain_number = activity.remain_number
                            activity_new_send_count = activity_origin_send_count - 1
                            activity_new_remain_number = activity_origin_remain_number + 1
                            result1 = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(
                                send_count=activity_new_send_count,
                                remain_number=activity_new_remain_number
                            )
                            if result1 == 0:
                                continue
                            break
                        try:
                            relation_set = alidiscountcoupon_level.child_set.all()
                            for relation in relation_set:
                                parent = relation.parent
                                parent.p_take_number -= 1
                                parent.p_receive_number -= 1
                                parent.p_remain_number += 1
                                parent.save()
                        except:
                            pass
                    qrcode.return_msg = result['sub_msg']
                    qrcode.qrcode_state = 1
                    qrcode.save()
                    try:
                        return Response({'error': result['sub_msg'], 'status': 0}, status=status.HTTP_400_BAD_REQUEST)
                    except:
                        return Response({'error': '领取失败,请联系管理员', 'status': 0}, status=status.HTTP_400_BAD_REQUEST)
                voucher_id = result['voucher_id']
                if activity.platform_id == 1:
                    result = json.loads(alipay_obj.voucherquery(voucher_id))
                    data = {
                        'alidiscountcoupon_id': activity.id,
                        'voucher_id': voucher_id,
                        'login_id': login_id,
                        'template_id': result['template_id'],
                        'gmt_active': result['gmt_active'],
                        'gmt_expired': result['gmt_expired'],
                        'total_amount': result['total_amount'],
                        'gmt_create': result['gmt_create'],
                        'available_amount': result['available_amount'],
                        'name': result['name'],
                        'out_biz_no': out_biz_no,
                        'customeruservice_id': user.id,
                        'gmt_distributed': datetime.datetime.now(),
                        'mobile': user.mobile,
                        'companyuser_id': qrcode.companyuser_id,
                        'level_id': alidiscountcoupon_level.level_id,
                        'alidiscountcoupon_level_id': alidiscountcoupon_level.id,
                        'coupon_channel': activity.coupon_channel
                    }
                else:
                    gmt_create = datetime.datetime.now()
                    alidiscountcouponchannelcommonvoucher = activity.alidiscountcouponchannelcommonvoucher
                    if alidiscountcouponchannelcommonvoucher.usetime_type == 2:
                        gmt_expired = alidiscountcouponchannelcommonvoucher.end_fixed_time
                        gmt_active = alidiscountcouponchannelcommonvoucher.start_fixed_time
                    elif alidiscountcouponchannelcommonvoucher.usetime_type == 3:
                        gmt_expired = gmt_create + datetime.timedelta(days=alidiscountcouponchannelcommonvoucher.invalid_day)
                        gmt_active = gmt_create
                    else:
                        gmt_active = (gmt_create + datetime.timedelta(days=1)).strftime("%Y-%m-%d 00:00:00")
                        gmt_expired = (gmt_create + datetime.timedelta(days=alidiscountcouponchannelcommonvoucher.invalid_day)).strftime("%Y-%m-%d 23:59:59")
                    data = {
                        'alidiscountcoupon_id': activity.id,
                        'voucher_id': voucher_id,
                        'login_id': login_id,
                        'template_id': activity.template_id,
                        'gmt_active': gmt_active,
                        'gmt_expired': gmt_expired,
                        'total_amount': activity.amount,
                        'gmt_create': gmt_create,
                        'available_amount': activity.amount,
                        'name': activity.activity_name,
                        'out_biz_no': out_biz_no,
                        'customeruservice_id': user.id,
                        'gmt_distributed': datetime.datetime.now(),
                        'mobile': user.mobile,
                        'companyuser_id': qrcode.companyuser_id,
                        'level_id': alidiscountcoupon_level.level_id,
                        'alidiscountcoupon_level_id': alidiscountcoupon_level.id,
                        'coupon_channel': activity.coupon_channel
                    }
                voucherinfo, create = AliDiscountCouponInfo.objects.get_or_create(defaults=data, voucher_id=voucher_id)
                if create:
                    return Response({'success': '领取成功', 'coupon_id': voucherinfo.id}, status=status.HTTP_200_OK)
                else:
                    return Response({'error': '已经领取过了', 'status': 0}, status=status.HTTP_400_BAD_REQUEST)
            elif activity.coupon_channel == 2:
                appid = settings.CUSTOMER_APP_ID_WYH
                openid = user.wyh_openid
                if activity.platform_id == 13:
                    distribute_channel = Channel.objects.get(id=13)
                else:
                    distribute_channel = Channel.objects.get(id=9)
                data_json = {
                    "stock_id": activity.template_id,
                    "out_request_no": out_biz_no,
                    "appid": appid,
                    "stock_creator_mchid": activity.platform.mchid
                }
                data_dict = favor_distributed_coupons_sichun(data_json, openid, distribute_channel)
                if 'code' in data_dict:
                    if activity.coupon_way == 4:
                        while True:
                            activity = AliDiscountCoupon.objects.get(id=activity_id)
                            activity_origin_send_count = activity.send_count
                            activity_origin_remain_number = activity.remain_number
                            activity_new_send_count = activity_origin_send_count - 1
                            activity_new_remain_number = activity_origin_remain_number + 1
                            result1 = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(
                                send_count=activity_new_send_count,
                                remain_number=activity_new_remain_number
                            )
                            if result1 == 0:
                                continue
                            break
                        while True:
                            alidiscountcoupon_level = AliDiscountCouponLevel.objects.get(id=alidiscountcoupon_level_id)
                            instance_origin_take_number = alidiscountcoupon_level.take_number
                            instance_origin_receive_number = alidiscountcoupon_level.receive_number
                            instance_origin_max_number = alidiscountcoupon_level.max_number
                            instance_origin_p_take_number = alidiscountcoupon_level.p_take_number
                            instance_origin_p_receive_number = alidiscountcoupon_level.p_receive_number
                            instance_origin_p_max_number = alidiscountcoupon_level.p_max_number
                            instance_new_take_number = instance_origin_take_number - 1
                            instance_new_receive_number = instance_origin_receive_number - 1
                            instance_new_max_number = instance_origin_max_number - 1
                            instance_new_p_take_number = instance_origin_p_take_number + 1
                            instance_new_p_receive_number = instance_origin_p_receive_number - 1
                            instance_new_p_max_number = instance_origin_p_max_number - 1
                            result1 = AliDiscountCouponLevel.objects.filter(id=alidiscountcoupon_level_id, take_number=instance_origin_take_number).update(
                                take_number=instance_new_take_number,
                                receive_number=instance_new_receive_number,
                                max_number=instance_new_max_number,
                                p_take_number=instance_new_p_take_number,
                                p_receive_number=instance_new_p_receive_number,
                                p_max_number=instance_new_p_max_number
                            )
                            if result1 == 0:
                                continue
                            break
                        try:
                            relation_set = alidiscountcoupon_level.child_set.all()
                            for relation in relation_set:
                                parent = relation.parent
                                parent.p_take_number -= 1
                                parent.p_receive_number -= 1
                                parent.p_max_number -= 1
                                parent.save()
                        except:
                            pass
                    else:
                        while True:
                            alidiscountcoupon_level = AliDiscountCouponLevel.objects.get(id=alidiscountcoupon_level_id)
                            instance_origin_take_number = alidiscountcoupon_level.take_number
                            instance_origin_receive_number = alidiscountcoupon_level.receive_number
                            instance_origin_remain_number = alidiscountcoupon_level.remain_number
                            instance_origin_p_take_number = alidiscountcoupon_level.p_take_number
                            instance_origin_p_receive_number = alidiscountcoupon_level.p_receive_number
                            instance_origin_p_remain_number = alidiscountcoupon_level.p_remain_number
                            instance_new_take_number = instance_origin_take_number - 1
                            instance_new_receive_number = instance_origin_receive_number - 1
                            instance_new_remain_number = instance_origin_remain_number + 1
                            instance_new_p_take_number = instance_origin_p_take_number - 1
                            instance_new_p_receive_number = instance_origin_p_receive_number - 1
                            instance_new_p_remain_number = instance_origin_p_remain_number + 1
                            result1 = AliDiscountCouponLevel.objects.filter(id=alidiscountcoupon_level_id, take_number=instance_origin_take_number).update(
                                take_number=instance_new_take_number,
                                receive_number=instance_new_receive_number,
                                remain_number=instance_new_remain_number,
                                p_take_number=instance_new_p_take_number,
                                p_receive_number=instance_new_p_receive_number,
                                p_remain_number=instance_new_p_remain_number
                            )
                            if result1 == 0:
                                continue
                            break
                        while True:
                            activity = AliDiscountCoupon.objects.get(id=activity_id)
                            activity_origin_send_count = activity.send_count
                            activity_origin_remain_number = activity.remain_number
                            activity_new_send_count = activity_origin_send_count - 1
                            activity_new_remain_number = activity_origin_remain_number + 1
                            result1 = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(
                                send_count=activity_new_send_count,
                                remain_number=activity_new_remain_number
                            )
                            if result1 == 0:
                                continue
                            break
                        try:
                            relation_set = alidiscountcoupon_level.child_set.all()
                            for relation in relation_set:
                                parent = relation.parent
                                parent.p_take_number -= 1
                                parent.p_receive_number -= 1
                                parent.p_remain_number += 1
                                parent.save()
                        except:
                            pass
                    return Response({'error': data_dict['message'], 'status': 0}, status=status.HTTP_400_BAD_REQUEST)
                coupon_id = data_dict['coupon_id']
                result = favor_query_coupons_sichun(coupon_id, openid, appid, distribute_channel)
                data = {
                    'alidiscountcoupon_id': activity.id,
                    'voucher_id': coupon_id,
                    'user_id': openid,
                    'appid': appid,
                    'template_id': result['stock_id'],
                    'gmt_active': result['available_begin_time'].replace('T', ' ').replace('+08:00', ''),
                    'gmt_expired': result['available_end_time'].replace('T', ' ').replace('+08:00', ''),
                    'total_amount': result['normal_coupon_information']['coupon_amount'] / 100,
                    'gmt_create': datetime.datetime.now(),
                    'available_amount': result['normal_coupon_information']['coupon_amount'] / 100,
                    'name': result['coupon_name'],
                    'out_biz_no': out_biz_no,
                    'customeruservice_id': user.id,
                    'gmt_distributed': datetime.datetime.now(),
                    'mobile': user.mobile,
                    'mobile_bank_identify': mobile_bank_identify,
                    'companyuser_id': qrcode.companyuser_id,
                    'level_id': alidiscountcoupon_level.level_id,
                    'alidiscountcoupon_level_id': alidiscountcoupon_level.id,
                    'coupon_channel': activity.coupon_channel
                }
                if not user.level_id:
                    user.level_id = alidiscountcoupon_level.level_id
                    user.user_id = qrcode.companyuser_id
                    user.save()
                voucherinfo, create = AliDiscountCouponInfo.objects.get_or_create(defaults=data, voucher_id=coupon_id)
                if create:
                    return Response({'success': '领取成功', 'coupon_id': voucherinfo.id}, status=status.HTTP_200_OK)
                else:
                    return Response({'error': '已经领取过了', 'status': 0}, status=status.HTTP_400_BAD_REQUEST)
            else:
                voucher_id = f'{datetime.datetime.now().strftime("%Y%m%d%H%M%S")}{random_str(14)}'
                gmt_create = datetime.datetime.now()
                alidiscountcouponchannelcommonvoucher = activity.alidiscountcouponchannelcommonvoucher
                if alidiscountcouponchannelcommonvoucher.usetime_type == 2:
                    gmt_expired = alidiscountcouponchannelcommonvoucher.end_fixed_time
                    gmt_active = alidiscountcouponchannelcommonvoucher.start_fixed_time
                elif alidiscountcouponchannelcommonvoucher.usetime_type == 3:
                    gmt_expired = gmt_create + datetime.timedelta(days=alidiscountcouponchannelcommonvoucher.invalid_day)
                    gmt_active = gmt_create
                else:
                    gmt_active = (gmt_create + datetime.timedelta(days=1)).strftime("%Y-%m-%d 00:00:00")
                    gmt_expired =(gmt_create+ datetime.timedelta(days=alidiscountcouponchannelcommonvoucher.invalid_day)).strftime("%Y-%m-%d 23:59:59")
                data = {
                    'alidiscountcoupon_id': activity.id,
                    'voucher_id': voucher_id,
                    'template_id': activity.template_id,
                    'gmt_active': gmt_active,
                    'gmt_expired': gmt_expired,
                    'total_amount': activity.amount,
                    'gmt_create': gmt_create,
                    'available_amount': activity.amount,
                    'name': activity.activity_name,
                    'out_biz_no': out_biz_no,
                    'customeruservice_id': user.id,
                    'companyuser_id': qrcode.companyuser_id,
                    'gmt_distributed': qrcode.gmt_distributed,
                    'alidiscountcoupon_level_id': alidiscountcoupon_level.id,
                    'level_id': alidiscountcoupon_level.level_id,
                    'mobile': user.mobile,
                    'coupon_channel': activity.coupon_channel
                }
                if not user.level_id:
                    user.level_id = alidiscountcoupon_level.level_id
                    user.user_id = qrcode.companyuser_id
                    user.save()
                voucherinfo, create = AliDiscountCouponInfo.objects.get_or_create(defaults=data, out_biz_no=out_biz_no)
                if create:
                    return Response({'success': '领取成功', 'coupon_id': voucherinfo.id}, status=status.HTTP_200_OK)
                else:
                    return Response({'error': '已经领取过了', 'status': 0}, status=status.HTTP_400_BAD_REQUEST)
        elif len(identify) == 64:
            try:
                alidiscountcoupon_level = AliDiscountCouponLevel.objects.get(identify=identify)
            except:
                return Response({'error': '无效二维码,请联系管理员'}, status=status.HTTP_400_BAD_REQUEST)
            activity = alidiscountcoupon_level.activity
            if activity.coupon_channel != 5:
                out_biz_no = f'100004{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}'
            else:
                out_biz_no = f'{datetime.datetime.now().strftime("%Y%m%d%H%M%S")}{"%04d" % randint(0, 9999)}'
            try:
                channelcommonvoucher = activity.alidiscountcouponchannelcommonvoucher
                if channelcommonvoucher.distributed_limit_by_time == 1:
                    week = str(datetime.datetime.now().weekday())
                    enable_time = datetime.datetime.now().strftime('1970-01-01 %H:%M:%S')
                    alidiscountcoupondstributedlimit = AliDiscountCouponDistributedLimit.objects.filter(ali_discount_coupon_common_voucher_id=channelcommonvoucher.id, weeks__contains=week, start_enable_time__lte=enable_time, end_enable_time__gte=enable_time)
                    if not alidiscountcoupondstributedlimit:
                        return Response({'error': '没到活动派发时间'}, status=status.HTTP_400_BAD_REQUEST)
                # if channelcommonvoucher.join_limit_by_user == 1:
                #     max_no = AliDiscountCouponInfo.objects.filter(alidiscountcoupon_id=activity.id, customeruservice_id=user.id).count()
                #     if max_no >= channelcommonvoucher.join_limit_by_user_count:
                #         return Response({'error': '活动中奖账户终身维度次数超过限制！'}, status=status.HTTP_400_BAD_REQUEST)
            except:
                pass
            query = AliDiscountCouponInfo.objects.filter(customer_user_id=user.id, alidiscountcoupon_id=activity.id)
            if 1 in query.values_list('status', flat=True):
                return Response({'error': '活动设定领1张使用1张规则'}, status=status.HTTP_400_BAD_REQUEST)
            elif activity.max_number_by_user <= query.count():
                return Response({'error': '活动已达到领取上限'}, status=status.HTTP_400_BAD_REQUEST)
            if activity.is_white:
                is_white = AliDiscountCouponWhiteTable.objects.filter(mobile=user.mobile, alidiscountcoupon_id=activity.id)
                if not is_white:
                    return Response({'error': '您没有该优惠券领取权限，请联系客户经理参与活动。'}, status=status.HTTP_400_BAD_REQUEST)
            if activity.is_check_identity == 1:
                check_manager = User.objects.filter(mobile=user.mobile, is_active=1)
                if check_manager:
                    return Response({'error': '该活动暂不允许内部员工领取，如有疑问请咨询客服。'}, status=status.HTTP_400_BAD_REQUEST)
            if user.is_auth != 2 and activity.is_need_auth == 1:
                return Response({'error': '请先完成实名认证'}, status=status.HTTP_400_BAD_REQUEST)
            if activity.max_number_by_day:
                begin_time = datetime.datetime.now().strftime('%Y-%m-%d 00:00:00')
                end_time = datetime.datetime.now().strftime('%Y-%m-%d 23:59:59')
                max_no = AliDiscountCouponInfo.objects.filter(alidiscountcoupon_id=activity.id, gmt_create__gte=begin_time,gmt_create__lte=end_time).count()
                if max_no >= activity.max_number_by_day:
                    return Response({'error': '今天的优惠券已领取完毕，请明天0点继续参与，感谢您对本活动的支持！'}, status=status.HTTP_400_BAD_REQUEST)
            if activity.remain_number <= 0:
                return Response({'error': '活动已达到派发上限'}, status=status.HTTP_400_BAD_REQUEST)
            alidiscountcoupon_level_id = alidiscountcoupon_level.id
            activity_id = activity.id
            while True:
                activity = AliDiscountCoupon.objects.get(id=activity_id)
                if activity.remain_number <= 0:
                    return Response({'error': '活动已达到派发上限'}, status=status.HTTP_400_BAD_REQUEST)
                activity_origin_send_count = activity.send_count
                activity_origin_remain_number = activity.remain_number
                activity_new_send_count = activity_origin_send_count + 1
                activity_new_remain_number = activity_origin_remain_number - 1
                result = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(
                    send_count=activity_new_send_count,
                    remain_number=activity_new_remain_number
                )
                if result == 0:
                    continue
                break
            while True:
                alidiscountcoupon_level = AliDiscountCouponLevel.objects.get(id=alidiscountcoupon_level_id)
                instance_origin_take_number = alidiscountcoupon_level.take_number
                instance_origin_receive_number = alidiscountcoupon_level.receive_number
                instance_origin_max_number = alidiscountcoupon_level.max_number
                instance_origin_p_take_number = alidiscountcoupon_level.p_take_number
                instance_origin_p_receive_number = alidiscountcoupon_level.p_receive_number
                instance_origin_p_max_number = alidiscountcoupon_level.p_max_number
                instance_new_take_number = instance_origin_take_number + 1
                instance_new_receive_number = instance_origin_receive_number + 1
                instance_new_max_number = instance_origin_max_number + 1
                instance_new_p_take_number = instance_origin_p_take_number + 1
                instance_new_p_receive_number = instance_origin_p_receive_number + 1
                instance_new_p_max_number = instance_origin_p_max_number + 1
                result = AliDiscountCouponLevel.objects.filter(id=alidiscountcoupon_level_id, take_number=instance_origin_take_number).update(
                    take_number=instance_new_take_number,
                    receive_number=instance_new_receive_number,
                    max_number=instance_new_max_number,
                    p_take_number=instance_new_p_take_number,
                    p_receive_number=instance_new_p_receive_number,
                    p_max_number=instance_new_p_max_number,
                )
                if result == 0:
                    continue
                break
            try:
                relation_set = alidiscountcoupon_level.child_set.all()
                for relation in relation_set:
                    parent = relation.parent
                    parent.p_take_number += 1
                    parent.p_receive_number += 1
                    parent.p_max_number += 1
                    parent.save()
            except:
                pass
            if activity.coupon_channel == 1:
                if not login_id:
                    while True:
                        activity = AliDiscountCoupon.objects.get(id=activity_id)
                        activity_origin_send_count = activity.send_count
                        activity_origin_remain_number = activity.remain_number
                        activity_new_send_count = activity_origin_send_count - 1
                        activity_new_remain_number = activity_origin_remain_number + 1
                        result1 = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(
                            send_count=activity_new_send_count,
                            remain_number=activity_new_remain_number
                        )
                        if result1 == 0:
                            continue
                        break
                    while True:
                        alidiscountcoupon_level = AliDiscountCouponLevel.objects.get(id=alidiscountcoupon_level_id)
                        instance_origin_take_number = alidiscountcoupon_level.take_number
                        instance_origin_receive_number = alidiscountcoupon_level.receive_number
                        instance_origin_max_number = alidiscountcoupon_level.max_number
                        instance_origin_p_take_number = alidiscountcoupon_level.p_take_number
                        instance_origin_p_receive_number = alidiscountcoupon_level.p_receive_number
                        instance_origin_p_max_number = alidiscountcoupon_level.p_max_number
                        instance_new_take_number = instance_origin_take_number - 1
                        instance_new_receive_number = instance_origin_receive_number - 1
                        instance_new_max_number = instance_origin_max_number - 1
                        instance_new_p_take_number = instance_origin_p_take_number - 1
                        instance_new_p_receive_number = instance_origin_p_receive_number - 1
                        instance_new_p_max_number = instance_origin_p_max_number - 1
                        result1 = AliDiscountCouponLevel.objects.filter(id=alidiscountcoupon_level_id, take_number=instance_origin_take_number).update(
                            take_number=instance_new_take_number,
                            receive_number=instance_new_receive_number,
                            max_number=instance_new_max_number,
                            p_take_number=instance_new_p_take_number,
                            p_receive_number=instance_new_p_receive_number,
                            p_max_number=instance_new_p_max_number
                        )
                        if result1 == 0:
                            continue
                        break
                    try:
                        relation_set = alidiscountcoupon_level.child_set.all()
                        for relation in relation_set:
                            parent = relation.parent
                            parent.p_take_number -= 1
                            parent.p_receive_number -= 1
                            parent.p_max_number -= 1
                            parent.save()
                    except:
                        pass
                    return Response({'error': '请上传支付宝账号', 'status': 0}, status=status.HTTP_400_BAD_REQUEST)
                alipay_obj = AlipayOpen()
                template_id = activity.template_id
                if activity.coupon_type == 11:
                    result = json.loads(alipay_obj.campaign_drawcamp_trigger_login_id(login_id, template_id, out_biz_no))
                else:
                    result = json.loads(alipay_obj.vouchersend_login_id(login_id, template_id, out_biz_no))
                if result['code'] != '10000':
                    logger.error(str(result))
                    while True:
                        activity = AliDiscountCoupon.objects.get(id=activity_id)
                        activity_origin_send_count = activity.send_count
                        activity_origin_remain_number = activity.remain_number
                        activity_new_send_count = activity_origin_send_count - 1
                        activity_new_remain_number = activity_origin_remain_number + 1
                        result1 = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(
                            send_count=activity_new_send_count,
                            remain_number=activity_new_remain_number
                        )
                        if result1 == 0:
                            continue
                        break
                    while True:
                        alidiscountcoupon_level = AliDiscountCouponLevel.objects.get(id=alidiscountcoupon_level_id)
                        instance_origin_take_number = alidiscountcoupon_level.take_number
                        instance_origin_receive_number = alidiscountcoupon_level.receive_number
                        instance_origin_max_number = alidiscountcoupon_level.max_number
                        instance_origin_p_take_number = alidiscountcoupon_level.p_take_number
                        instance_origin_p_receive_number = alidiscountcoupon_level.p_receive_number
                        instance_origin_p_max_number = alidiscountcoupon_level.p_max_number
                        instance_new_take_number = instance_origin_take_number - 1
                        instance_new_receive_number = instance_origin_receive_number - 1
                        instance_new_max_number = instance_origin_max_number - 1
                        instance_new_p_take_number = instance_origin_p_take_number - 1
                        instance_new_p_receive_number = instance_origin_p_receive_number - 1
                        instance_new_p_max_number = instance_origin_p_max_number - 1
                        result1 = AliDiscountCouponLevel.objects.filter(id=alidiscountcoupon_level_id, take_number=instance_origin_take_number).update(
                            take_number=instance_new_take_number,
                            receive_number=instance_new_receive_number,
                            max_number=instance_new_max_number,
                            p_take_number=instance_new_p_take_number,
                            p_receive_number=instance_new_p_receive_number,
                            p_max_number=instance_new_p_max_number
                        )
                        if result1 == 0:
                            continue
                        break
                    try:
                        relation_set = alidiscountcoupon_level.child_set.all()
                        for relation in relation_set:
                            parent = relation.parent
                            parent.p_take_number -= 1
                            parent.p_receive_number -= 1
                            parent.p_max_number -= 1
                            parent.save()
                    except:
                        pass
                    try:
                        return Response({'error': result['sub_msg'], 'status': 0}, status=status.HTTP_400_BAD_REQUEST)
                    except:
                        return Response({'error': '领取失败,请联系管理员', 'status': 0}, status=status.HTTP_400_BAD_REQUEST)
                if activity.coupon_type == 11:
                    if not result['trigger_result']:
                        logger.error(str(result))
                        while True:
                            activity = AliDiscountCoupon.objects.get(id=activity_id)
                            activity_origin_send_count = activity.send_count
                            activity_origin_remain_number = activity.remain_number
                            activity_new_send_count = activity_origin_send_count - 1
                            activity_new_remain_number = activity_origin_remain_number + 1
                            result1 = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(
                                send_count=activity_new_send_count,
                                remain_number=activity_new_remain_number
                            )
                            if result1 == 0:
                                continue
                            break
                        while True:
                            alidiscountcoupon_level = AliDiscountCouponLevel.objects.get(id=alidiscountcoupon_level_id)
                            instance_origin_take_number = alidiscountcoupon_level.take_number
                            instance_origin_receive_number = alidiscountcoupon_level.receive_number
                            instance_origin_max_number = alidiscountcoupon_level.max_number
                            instance_origin_p_take_number = alidiscountcoupon_level.p_take_number
                            instance_origin_p_receive_number = alidiscountcoupon_level.p_receive_number
                            instance_origin_p_max_number = alidiscountcoupon_level.p_max_number
                            instance_new_take_number = instance_origin_take_number - 1
                            instance_new_receive_number = instance_origin_receive_number - 1
                            instance_new_max_number = instance_origin_max_number - 1
                            instance_new_p_take_number = instance_origin_p_take_number - 1
                            instance_new_p_receive_number = instance_origin_p_receive_number - 1
                            instance_new_p_max_number = instance_origin_p_max_number - 1
                            result1 = AliDiscountCouponLevel.objects.filter(id=alidiscountcoupon_level_id, take_number=instance_origin_take_number).update(
                                take_number=instance_new_take_number,
                                receive_number=instance_new_receive_number,
                                max_number=instance_new_max_number,
                                p_take_number=instance_new_p_take_number,
                                p_receive_number=instance_new_p_receive_number,
                                p_max_number=instance_new_p_max_number
                            )
                            if result1 == 0:
                                continue
                            break
                        try:
                            relation_set = alidiscountcoupon_level.child_set.all()
                            for relation in relation_set:
                                parent = relation.parent
                                parent.p_take_number -= 1
                                parent.p_receive_number -= 1
                                parent.p_max_number -= 1
                                parent.save()
                        except:
                            pass
                        try:
                            return Response({'error': json.loads(result['extend_field'])['errorMsg'], 'status': 0}, status=status.HTTP_400_BAD_REQUEST)
                        except:
                            return Response({'error': '领取失败,请联系管理员', 'status': 0}, status=status.HTTP_400_BAD_REQUEST)
                    voucher_id = result['out_prize_id']
                else:
                    voucher_id = result['voucher_id']
                if activity.platform_id == 1:
                    result = json.loads(alipay_obj.voucherquery(voucher_id))
                    data = {
                        'alidiscountcoupon_id': activity.id,
                        'voucher_id': voucher_id,
                        'login_id': login_id,
                        'template_id': result['template_id'],
                        'gmt_active': result['gmt_active'],
                        'gmt_expired': result['gmt_expired'],
                        'total_amount': result['total_amount'],
                        'gmt_create': result['gmt_create'],
                        'available_amount': result['available_amount'],
                        'name': result['name'],
                        'out_biz_no': out_biz_no,
                        'customeruservice_id': user.id,
                        'gmt_distributed': datetime.datetime.now(),
                        'mobile': user.mobile,
                        'level_id': alidiscountcoupon_level.level_id,
                        'alidiscountcoupon_level_id': alidiscountcoupon_level.id,
                        'coupon_channel': activity.coupon_channel
                    }
                else:
                    gmt_create = datetime.datetime.now()
                    alidiscountcouponchannelcommonvoucher = activity.alidiscountcouponchannelcommonvoucher
                    if alidiscountcouponchannelcommonvoucher.usetime_type == 2:
                        gmt_expired = alidiscountcouponchannelcommonvoucher.end_fixed_time
                        gmt_active = alidiscountcouponchannelcommonvoucher.start_fixed_time
                    elif alidiscountcouponchannelcommonvoucher.usetime_type == 3:
                        gmt_expired = gmt_create + datetime.timedelta(days=alidiscountcouponchannelcommonvoucher.invalid_day)
                        gmt_active = gmt_create
                    else:
                        gmt_active = (gmt_create + datetime.timedelta(days=1)).strftime("%Y-%m-%d 00:00:00")
                        gmt_expired = (gmt_create + datetime.timedelta(days=alidiscountcouponchannelcommonvoucher.invalid_day)).strftime("%Y-%m-%d 23:59:59")
                    data = {
                        'alidiscountcoupon_id': activity.id,
                        'voucher_id': voucher_id,
                        'login_id': login_id,
                        'template_id': activity.template_id,
                        'gmt_active': gmt_active,
                        'gmt_expired': gmt_expired,
                        'total_amount': activity.amount,
                        'gmt_create': gmt_create,
                        'available_amount': activity.amount,
                        'name': activity.activity_name,
                        'out_biz_no': out_biz_no,
                        'customeruservice_id': user.id,
                        'gmt_distributed': datetime.datetime.now(),
                        'mobile': user.mobile,
                        'level_id': alidiscountcoupon_level.level_id,
                        'alidiscountcoupon_level_id': alidiscountcoupon_level.id,
                        'coupon_channel': activity.coupon_channel
                    }
                voucherinfo, create = AliDiscountCouponInfo.objects.get_or_create(defaults=data, voucher_id=voucher_id)
                # else:
                #     if result['trigger_result']:
                #         voucher_id = result['prize_flag']
                #     else:
                #         voucher_id = ''
                #     gmt_create = datetime.datetime.now()
                #     alidiscountcouponchannelcommonvoucher = activity.alidiscountcouponchannelcommonvoucher
                #     if alidiscountcouponchannelcommonvoucher.usetime_type == 2:
                #         gmt_expired = alidiscountcouponchannelcommonvoucher.end_fixed_time
                #         gmt_active = alidiscountcouponchannelcommonvoucher.start_fixed_time
                #     elif alidiscountcouponchannelcommonvoucher.usetime_type == 3:
                #         gmt_expired = gmt_create + datetime.timedelta(
                #             days=alidiscountcouponchannelcommonvoucher.invalid_day)
                #         gmt_active = gmt_create
                #     else:
                #         gmt_active = (gmt_create + datetime.timedelta(days=1)).strftime("%Y-%m-%d 00:00:00")
                #         gmt_expired = (gmt_create + datetime.timedelta(days=alidiscountcouponchannelcommonvoucher.invalid_day)).strftime("%Y-%m-%d 23:59:59")
                #     data = {
                #         'alidiscountcoupon_id': activity.id,
                #         'login_id': login_id,
                #         'voucher_id': voucher_id,
                #         'template_id': activity.template_id,
                #         'gmt_active': gmt_active,
                #         'gmt_expired': gmt_expired,
                #         'gmt_create': gmt_create,
                #         'name': activity.activity_name,
                #         'out_biz_no': out_biz_no,
                #         'customeruservice_id': user.id,
                #         'gmt_distributed': datetime.datetime.now(),
                #         'mobile': user.mobile,
                #         'level_id': alidiscountcoupon_level.level_id,
                #         'alidiscountcoupon_level_id': alidiscountcoupon_level.id,
                #         'coupon_channel': activity.coupon_channel
                #     }
                #     voucherinfo, create = AliDiscountCouponInfo.objects.create(**data)
                #     AliDiscountCouponInfoCampaignDrawcampTrigger.objects.create(voucherinfo_id=voucherinfo.id, result=json.dumps(result))
                if create:
                    return Response({'success': '领取成功', 'coupon_id': voucherinfo.id}, status=status.HTTP_200_OK)
                else:
                    return Response({'error': '已经领取过了', 'status': 0}, status=status.HTTP_400_BAD_REQUEST)

        else:
            return Response({'error': '无效二维码参数', 'status': 0}, status=status.HTTP_400_BAD_REQUEST)


        # if not identify:
        #     return Response({'error': '缺少必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        # try:
        #     activity = AliDiscountCoupon.objects.get(template_id=identify, coupon_way=8)
        # except:
        #     return Response({'error': '无效活动参数,请联系管理员'}, status=status.HTTP_400_BAD_REQUEST)
        # if activity.coupon_status != 1:
        #     return Response({'error': '活动已结束'}, status=status.HTTP_400_BAD_REQUEST)
        # if activity.remain_number <= 0:
        #     return Response({'error': '活动已达到派发上限'}, status=status.HTTP_400_BAD_REQUEST)
        # out_biz_no = f'{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}{"%07d" % user.id}'
        # channelcommonvoucher = activity.alidiscountcouponchannelcommonvoucher
        # if channelcommonvoucher.distributed_limit_by_time == 1:
        #     week = str(datetime.datetime.now().weekday())
        #     enable_time = datetime.datetime.now().strftime('1970-01-01 %H:%M:%S')
        #     alidiscountcoupondstributedlimit = AliDiscountCouponDistributedLimit.objects.filter(
        #         ali_discount_coupon_common_voucher_id=channelcommonvoucher.id, weeks__contains=week,
        #         start_enable_time__lte=enable_time, end_enable_time__gte=enable_time)
        #     if not alidiscountcoupondstributedlimit:
        #         return Response({'error': '没到活动派发时间'}, status=status.HTTP_400_BAD_REQUEST)
        # if activity.is_white:
        #     is_white = AliDiscountCouponWhiteTable.objects.filter(mobile=user.mobile, alidiscountcoupon_id=activity.id)
        #     if not is_white:
        #         return Response({'error': '您没有该优惠券领取权限，请联系客户经理参与活动。'}, status=status.HTTP_400_BAD_REQUEST)
        # if activity.max_number_by_day:
        #     begin_time = datetime.datetime.now().strftime('%Y-%m-%d 00:00:00')
        #     end_time = datetime.datetime.now().strftime('%Y-%m-%d 23:59:59')
        #     max_no = AliDiscountCouponInfo.objects.filter(alidiscountcoupon_id=activity.id,
        #                                                   gmt_create__gte=begin_time,
        #                                                   gmt_create__lte=end_time).count()
        #     if max_no >= activity.max_number_by_day:
        #         return Response({'error': '今天的优惠券已领取完毕，请明天0点继续参与，感谢您对本活动的支持！'}, status=status.HTTP_400_BAD_REQUEST)
        # if channelcommonvoucher.join_limit_by_user:
        #     max_no = AliDiscountCouponInfo.objects.filter(alidiscountcoupon_id=activity.id, customeruservice_id=user.id).count()
        #     if max_no >= channelcommonvoucher.join_limit_by_user_count:
        #         return Response({'error': '用户参与活动次数已达上限，感谢您对本活动的支持！'}, status=status.HTTP_400_BAD_REQUEST)
        # if activity.remain_number <= 0:
        #     return Response({'error': '活动已达到派发上限'}, status=status.HTTP_400_BAD_REQUEST)
        # if user.is_auth != 2 and activity.is_need_auth == 1:
        #     return Response({'error': '请先完成实名认证'}, status=status.HTTP_400_BAD_REQUEST)
        # if channelcommonvoucher.join_limit_by_location == 1:
        #     if not all([latitude, longitude]):
        #         return Response({'error': '请上传经纬度信息'}, status=status.HTTP_400_BAD_REQUEST)
        #     check_location = AliDiscountCouponJoinLimitLocation.objects.filter(
        #         longitude_begin__lte=longitude,
        #         longitude_end__gte=longitude,
        #         latitude_begin__lte=latitude,
        #         latitude_end__gte=latitude,
        #         ali_discount_coupon_common_voucher_id=channelcommonvoucher.id
        #     )
        #     if not check_location:
        #         return Response({'error': '当前区域不支持参与该活动'}, status=status.HTTP_400_BAD_REQUEST)
        # activity_id = activity.id
        # while True:
        #     activity = AliDiscountCoupon.objects.get(id=activity_id)
        #     activity_origin_send_count = activity.send_count
        #     activity_origin_remain_number = activity.remain_number
        #     activity_new_send_count = activity_origin_send_count + 1
        #     activity_new_remain_number = activity_origin_remain_number - 1
        #     result = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(
        #         send_count=activity_new_send_count,
        #         remain_number=activity_new_remain_number
        #     )
        #     if result == 0:
        #         continue
        #     break
        # if activity.coupon_channel == 1:
        #     if not login_id:
        #         while True:
        #             activity = AliDiscountCoupon.objects.get(id=activity_id)
        #             activity_origin_send_count = activity.send_count
        #             activity_origin_remain_number = activity.remain_number
        #             activity_new_send_count = activity_origin_send_count - 1
        #             activity_new_remain_number = activity_origin_remain_number + 1
        #             result1 = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(
        #                 send_count=activity_new_send_count,
        #                 remain_number=activity_new_remain_number
        #             )
        #             if result1 == 0:
        #                 continue
        #             break
        #         return Response({'error': '请上传支付宝账号'}, status=status.HTTP_400_BAD_REQUEST)
        #     alipay_obj = AlipayOpen()
        #     template_id = activity.template_id
        #     result = json.loads(alipay_obj.vouchersend_login_id(login_id, template_id, out_biz_no))
        #     if result['code'] != '10000':
        #         logger.error(str(result))
        #         while True:
        #             activity = AliDiscountCoupon.objects.get(id=activity_id)
        #             activity_origin_send_count = activity.send_count
        #             activity_origin_remain_number = activity.remain_number
        #             activity_new_send_count = activity_origin_send_count - 1
        #             activity_new_remain_number = activity_origin_remain_number + 1
        #             result1 = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(
        #                 send_count=activity_new_send_count,
        #                 remain_number=activity_new_remain_number
        #             )
        #             if result1 == 0:
        #                 continue
        #             break
        #         try:
        #             return Response({'error': result['sub_msg']}, status=status.HTTP_400_BAD_REQUEST)
        #         except:
        #             return Response({'error': '领取失败,请联系管理员'}, status=status.HTTP_400_BAD_REQUEST)
        #     voucher_id = result['voucher_id']
        #     if activity.platform_id == 1:
        #         result = json.loads(alipay_obj.voucherquery(voucher_id))
        #         data = {
        #             'alidiscountcoupon_id': activity.id,
        #             'voucher_id': voucher_id,
        #             'login_id': login_id,
        #             'template_id': result['template_id'],
        #             'gmt_active': result['gmt_active'],
        #             'gmt_expired': result['gmt_expired'],
        #             'total_amount': result['total_amount'],
        #             'gmt_create': result['gmt_create'],
        #             'available_amount': result['available_amount'],
        #             'name': result['name'],
        #             'out_biz_no': out_biz_no,
        #             'customeruservice_id': user.id,
        #             'gmt_distributed': datetime.datetime.now(),
        #             'mobile': user.mobile,
        #             'mobile_bank_identify': mobile_bank_identify,
        #             'coupon_channel': activity.coupon_channel
        #         }
        #     else:
        #         gmt_create = datetime.datetime.now()
        #         alidiscountcouponchannelcommonvoucher = activity.alidiscountcouponchannelcommonvoucher
        #         if alidiscountcouponchannelcommonvoucher.usetime_type == 2:
        #             gmt_expired = alidiscountcouponchannelcommonvoucher.end_fixed_time
        #             gmt_active = alidiscountcouponchannelcommonvoucher.start_fixed_time
        #         elif alidiscountcouponchannelcommonvoucher.usetime_type == 3:
        #             gmt_expired = gmt_create + datetime.timedelta(days=alidiscountcouponchannelcommonvoucher.invalid_day)
        #             gmt_active = gmt_create
        #         else:
        #             gmt_active = (gmt_create + datetime.timedelta(days=1)).strftime("%Y-%m-%d 00:00:00")
        #             gmt_expired = (gmt_create + datetime.timedelta(days=alidiscountcouponchannelcommonvoucher.invalid_day)).strftime("%Y-%m-%d 23:59:59")
        #         data = {
        #             'alidiscountcoupon_id': activity.id,
        #             'voucher_id': voucher_id,
        #             'login_id': login_id,
        #             'template_id': activity.template_id,
        #             'gmt_active': gmt_active,
        #             'gmt_expired': gmt_expired,
        #             'total_amount': activity.amount,
        #             'gmt_create': gmt_create,
        #             'available_amount': activity.amount,
        #             'name': activity.activity_name,
        #             'out_biz_no': out_biz_no,
        #             'customeruservice_id': user.id,
        #             'gmt_distributed': datetime.datetime.now(),
        #             'mobile': user.mobile,
        #             'mobile_bank_identify': mobile_bank_identify,
        #             'coupon_channel': activity.coupon_channel
        #         }
        #     voucherinfo, create = AliDiscountCouponInfo.objects.get_or_create(defaults=data, voucher_id=voucher_id)
        #     if mobile_bank_identify and mobile_bank_identify != 'undefined':
        #         mobile_bank_vouchers_update.delay({"openId": mobile_bank_identify, "couponId": voucher_id, "stockId": activity.template_id, "status": "1"})
        #     if create:
        #         return Response({'success': '领取成功', 'coupon_id': voucherinfo.id}, status=status.HTTP_200_OK)
        #     else:
        #         return Response({'error': '已经领取过了'}, status=status.HTTP_400_BAD_REQUEST)
        # else:
        #     appid = settings.CUSTOMER_APP_ID_WYH
        #     openid = user.wyh_openid
        #     data_json = {
        #         "stock_id": activity.template_id,
        #         "out_request_no": out_biz_no,
        #         "appid": appid,
        #         "stock_creator_mchid": activity.platform.mchid
        #     }
        #     if activity.platform_id == 13:
        #         distribute_channel = Channel.objects.get(id=13)
        #     else:
        #         distribute_channel = Channel.objects.get(id=9)
        #     data_dict = favor_distributed_coupons_sichun(data_json, openid, distribute_channel)
        #     if 'code' in data_dict:
        #         logger.error(str(data_dict))
        #         while True:
        #             activity = AliDiscountCoupon.objects.get(id=activity_id)
        #             activity_origin_send_count = activity.send_count
        #             activity_origin_remain_number = activity.remain_number
        #             activity_new_send_count = activity_origin_send_count - 1
        #             activity_new_remain_number = activity_origin_remain_number + 1
        #             result1 = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(
        #                 send_count=activity_new_send_count,
        #                 remain_number=activity_new_remain_number
        #             )
        #             if result1 == 0:
        #                 continue
        #             break
        #         return Response({'error': data_dict['message']}, status=status.HTTP_400_BAD_REQUEST)
        #     coupon_id = data_dict['coupon_id']
        #     result = favor_query_coupons_sichun(coupon_id, openid, appid, distribute_channel)
        #     data = {
        #         'alidiscountcoupon_id': activity.id,
        #         'voucher_id': coupon_id,
        #         'user_id': openid,
        #         'appid': appid,
        #         'template_id': result['stock_id'],
        #         'gmt_active': result['available_begin_time'].replace('T', ' ').replace('+08:00', ''),
        #         'gmt_expired': result['available_end_time'].replace('T', ' ').replace('+08:00', ''),
        #         'total_amount': result['normal_coupon_information']['coupon_amount'] / 100,
        #         'gmt_create': datetime.datetime.now(),
        #         'available_amount': result['normal_coupon_information']['coupon_amount'] / 100,
        #         'name': result['coupon_name'],
        #         'out_biz_no': out_biz_no,
        #         'customeruservice_id': user.id,
        #         'gmt_distributed': datetime.datetime.now(),
        #         'mobile': user.mobile,
        #         'mobile_bank_identify': mobile_bank_identify,
        #         'coupon_channel': activity.coupon_channel
        #     }
        #     voucherinfo, create = AliDiscountCouponInfo.objects.get_or_create(defaults=data, voucher_id=coupon_id)
        #     if mobile_bank_identify and mobile_bank_identify != 'undefined':
        #         mobile_bank_vouchers_update.delay({"openId": mobile_bank_identify, "couponId": coupon_id, "stockId": activity.template_id, "status": "1"})
        #     if create:
        #         return Response({'success': '领取成功', 'coupon_id': voucherinfo.id}, status=status.HTTP_200_OK)
        #     else:
        #         return Response({'error': '已经领取过了'}, status=status.HTTP_400_BAD_REQUEST)

    def five_nineteen(self, request):
        user = self.request.iser
        datetime_now = datetime.datetime.now()
        # is_offline = self.request.query_params.get('is_offline', None)
        # activityset0 = AliDiscountCoupon.objects.filter(id__in=[27165, 27164]).order_by('-id')
        # activityset1 = AliDiscountCoupon.objects.filter(id__in=[27236, 27237])
        # activityset2 = AliDiscountCoupon.objects.filter(id__in=[27439, 27438]).order_by('-id')
        # activityset3 = AliDiscountCoupon.objects.filter(id__in=[27679, 27678]).order_by('-id')
        # activityset5 = AliDiscountCoupon.objects.filter(id__in=[27916, 27917])
        # activityset6 = AliDiscountCoupon.objects.filter(id__in=[28120, 28121])
        # activityset7 = AliDiscountCoupon.objects.filter(id__in=[28471, 28470])
        # activityset8 = AliDiscountCoupon.objects.filter(id__in=[28571, 28572]).order_by('-id')
        # activityset9 = AliDiscountCoupon.objects.filter(id=28743).order_by('-id')
        # activityset10 = AliDiscountCoupon.objects.filter(id=28853).order_by('-id')

        response_data = {
            "data": [
                {
                    "title": "第十轮抢券",
                    "publish_time": "07月29日 12:00-08月09日 23:59",
                    "lists": [
                        {
                            "floor_amount": "满200元减50元",
                            "available_merchants": "519指定旅游民宿可用",
                            "amount": 50.0,
                            "activity_id": "18860551",
                            "status": 3
                        }
                    ]
                },
                {
                    "title": "第一轮抢券",
                    "publish_time": "05月19日 12:00-05月25日 23:59",
                    "lists": [
                        {
                            "floor_amount": "满400元减100元",
                            "available_merchants": "519指定旅游民宿可用",
                            "amount": 100.0,
                            "activity_id": "18863349",
                            "status": 3
                        },
                        {
                            "floor_amount": "满200元减50元",
                            "available_merchants": "519指定旅游民宿可用",
                            "amount": 50.0,
                            "activity_id": "18860551",
                            "status": 3
                        }
                    ]
                },
                {
                    "title": "第二轮抢券",
                    "publish_time": "05月26日 12:00-06月01日 23:59",
                    "lists": [
                        {
                            "floor_amount": "满400元减100元",
                            "available_merchants": "519指定旅游民宿可用",
                            "amount": 100.0,
                            "activity_id": "18879215",
                            "status": 3
                        },
                        {
                            "floor_amount": "满200元减50元",
                            "available_merchants": "519指定旅游民宿可用",
                            "amount": 50.0,
                            "activity_id": "18879216",
                            "status": 3
                        }
                    ]
                },
                {
                    "title": "第三轮抢券",
                    "publish_time": "06月02日 12:00-06月08日 23:59",
                    "lists": [
                        {
                            "floor_amount": "满200元减50元",
                            "available_merchants": "",
                            "amount": 50.0,
                            "activity_id": "18939738",
                            "status": 3
                        },
                        {
                            "floor_amount": "满400元减100元",
                            "available_merchants": "519指定旅游民宿可用",
                            "amount": 100.0,
                            "activity_id": "18940037",
                            "status": 3
                        }
                    ]
                },
                {
                    "title": "第四轮抢券",
                    "publish_time": "06月09日 12:00-06月15日 23:59",
                    "lists": [
                        {
                            "floor_amount": "满400元减100元",
                            "available_merchants": "519指定旅游民宿可用",
                            "amount": 100.0,
                            "activity_id": "18972001",
                            "status": 3
                        },
                        {
                            "floor_amount": "满200元减50元",
                            "available_merchants": "519指定旅游民宿可用",
                            "amount": 50.0,
                            "activity_id": "18972894",
                            "status": 3
                        }
                    ]
                },
                {
                    "title": "第五轮抢券",
                    "publish_time": "06月16日 12:00-06月22日 23:59",
                    "lists": [
                        {
                            "floor_amount": "满400元减100元",
                            "available_merchants": "519指定旅游民宿可用",
                            "amount": 100.0,
                            "activity_id": "18863349",
                            "status": 3
                        },
                        {
                            "floor_amount": "满200元减50元",
                            "available_merchants": "519指定旅游民宿可用",
                            "amount": 50.0,
                            "activity_id": "18860551",
                            "status": 3
                        }
                    ]
                },
                {
                    "title": "第六轮抢券",
                    "publish_time": "06月23日 12:00-06月29日 23:59",
                    "lists": [
                        {
                            "floor_amount": "满400元减100元",
                            "available_merchants": "519指定旅游民宿可用",
                            "amount": 100.0,
                            "activity_id": "18863349",
                            "status": 3
                        },
                        {
                            "floor_amount": "满200元减50元",
                            "available_merchants": "519指定旅游民宿可用",
                            "amount": 50.0,
                            "activity_id": "18860551",
                            "status": 3
                        }
                    ]
                },
                {
                    "title": "第七轮抢券",
                    "publish_time": "07月08日 12:00-07月14日 23:59",
                    "lists": [
                        {
                            "floor_amount": "满400元减100元",
                            "available_merchants": "519指定旅游民宿可用",
                            "amount": 100.0,
                            "activity_id": "18863349",
                            "status": 3
                        },
                        {
                            "floor_amount": "满200元减50元",
                            "available_merchants": "519指定旅游民宿可用",
                            "amount": 50.0,
                            "activity_id": "18860551",
                            "status": 3
                        }
                    ]
                },
                {
                    "title": "第八轮抢券",
                    "publish_time": "07月15日 12:00-07月21日 23:59",
                    "lists": [
                        {
                            "floor_amount": "满400元减100元",
                            "available_merchants": "519指定旅游民宿可用",
                            "amount": 100.0,
                            "activity_id": "18863349",
                            "status": 3
                        },
                        {
                            "floor_amount": "满200元减50元",
                            "available_merchants": "519指定旅游民宿可用",
                            "amount": 50.0,
                            "activity_id": "18860551",
                            "status": 3
                        }
                    ]
                },
                {
                    "title": "第九轮抢券",
                    "publish_time": "07月22日 12:00-07月28日 23:59",
                    "lists": [
                        {
                            "floor_amount": "满200元减50元",
                            "available_merchants": "519指定旅游民宿可用",
                            "amount": 50.0,
                            "activity_id": "18860551",
                            "status": 3
                        }
                    ]
                },
            ],
            "description": "同一用户每轮最多可分别领取1张100元、50元旅游民宿消费券，不同轮次的消费券可多次领取，先到先得，领完即止；\n消费券自领取之日起7个自然日(含领券当日)内有效，逾期失效，超过使用期限未使用则视为自动放弃消费券，不予补发；\n领取旅游民宿消费券后，消费券自动同步至“微信卡包”中，可在微信app-我-卡包中查看并使用；\n100元旅游民宿消费券满400元可用、50元旅游民宿消费券满200元可用，仅限519旅游日活动指定旅游民宿；支持到店（线下519旅游民宿实体商家）消费，扫“微邮付”码牌付款；\n同类消费券在同一笔订单中，仅限使用1张，不设找零返现；\n旅游民宿消费券不可提现、拆分、退补或转赠，不支持部分订单金额退款。若整笔订单退款且发生退款时使用的旅游民宿消费券仍在有效期内，则退还用户实际支付金额(不包含旅游民宿消费券抵扣金额)以及已使用的旅游民宿消费券(有效期不予延长)；若整笔订单退款时所使用的旅游民宿消费券已过有效期，则退还用户实际支付的金额；\n为使更多的用户参与本消费券活动，对使用或涉嫌使用违反活动规则或不正当方式套取旅游消费券的用户及其所使用的工具包括但不限于手机号、银行卡号、APP账号等，主办方和商户有权不予优惠、追回已发放的消费券,并拒绝其今后参加主办方的任何优惠活动；\n旅游民宿消费券派发配比将在执行过程中根据实际效果适时调整；\n用户参与活动即视为理解并同意本活动细则。若用户在参与活动期间遇到任何疑问，可向微邮惠商圈客服或小邮美宿客服反映，我们将积极协调解决。"
        }

        # activity_dict = {}
        # activity_list = []
        # for activity in activityset10:
        #     activity_dict['title'] = f'第十轮抢券'
        #     activity_dict['publish_time'] = f"{activity.publish_start_time.strftime('%m月%d日 %H:%M')}-{activity.publish_end_time.strftime('%m月%d日 %H:%M')}"
        #     activity_data = {}
        #     activity_data['floor_amount'] = activity.floor_amount
        #     activity_data['available_merchants'] = activity.available_merchants
        #     activity_data['available_merchants'] = activity.available_merchants
        #     activity_data['amount'] = activity.amount
        #     activity_data['activity_id'] = activity.template_id
        #     if activity.publish_start_time > datetime_now:
        #         activity_data['status'] = 0
        #     else:
        #         check_coupon = AliDiscountCouponInfo.objects.filter(customeruservice_id=user.id, alidiscountcoupon_id=activity.id)
        #         if activity.publish_end_time > datetime_now:
        #             if check_coupon:
        #                 activity_data['status'] = 2
        #             else:
        #                 if activity.remain_number > 0:
        #                     activity_data['status'] = 1
        #                 else:
        #                     activity_data['status'] = 3
        #         else:
        #             if check_coupon:
        #                 activity_data['status'] = 2
        #             else:
        #                 activity_data['status'] = 3
        #     activity_list.append(activity_data)
        # activity_dict['lists'] = activity_list
        # response_data['data'][0] = activity_dict
        return Response(response_data, status=status.HTTP_200_OK)


        activity_list1 = [activityset4, activityset1, activityset2, activityset3]
        data = []
        N_ENUM = {
            1: '四',
            2: '一',
            3: '二',
            4: '三',
            5: '五'
        }
        n = 1
        for activityset in activity_list1:
            activity_dict = {}
            activity_list = []
            for activity in activityset:
                activity_dict['title'] = f'第{N_ENUM[n]}轮抢券'
                activity_dict['publish_time'] = f"{activity.publish_start_time.strftime('%m月%d日 %H:%M')}-{activity.publish_end_time.strftime('%m月%d日 %H:%M')}"
                activity_data = {}
                activity_data['floor_amount'] = activity.floor_amount
                activity_data['available_merchants'] = activity.available_merchants
                activity_data['available_merchants'] = activity.available_merchants
                activity_data['amount'] = activity.amount
                activity_data['activity_id'] = activity.template_id
                if activity.publish_start_time > datetime_now:
                    activity_data['status'] = 0
                else:
                    check_coupon = AliDiscountCouponInfo.objects.filter(customeruservice_id=user.id, alidiscountcoupon_id=activity.id)
                    if activity.publish_end_time > datetime_now:
                        if check_coupon:
                            activity_data['status'] = 2
                        else:
                            if activity.remain_number > 0:
                                activity_data['status'] = 1
                            else:
                                activity_data['status'] = 3
                    else:
                        if check_coupon:
                            activity_data['status'] = 2
                        else:
                            activity_data['status'] = 3
                activity_list.append(activity_data)
            n += 1
            activity_dict['lists'] = activity_list
            data.append(activity_dict)
        description = '''同一用户每轮最多可分别领取1张100元、50元旅游民宿消费券，不同轮次的消费券可多次领取，先到先得，领完即止；
消费券自领取之日起7个自然日(含领券当日)内有效，逾期失效，超过使用期限未使用则视为自动放弃消费券，不予补发；
领取旅游民宿消费券后，消费券自动同步至“微信卡包”中，可在微信app-我-卡包中查看并使用；
100元旅游民宿消费券满400元可用、50元旅游民宿消费券满200元可用，仅限519旅游日活动指定旅游民宿；支持到店（线下519旅游民宿实体商家）消费，扫“微邮付”码牌付款；
同类消费券在同一笔订单中，仅限使用1张，不设找零返现；
旅游民宿消费券不可提现、拆分、退补或转赠，不支持部分订单金额退款。若整笔订单退款且发生退款时使用的旅游民宿消费券仍在有效期内，则退还用户实际支付金额(不包含旅游民宿消费券抵扣金额)以及已使用的旅游民宿消费券(有效期不予延长)；若整笔订单退款时所使用的旅游民宿消费券已过有效期，则退还用户实际支付的金额；
为使更多的用户参与本消费券活动，对使用或涉嫌使用违反活动规则或不正当方式套取旅游消费券的用户及其所使用的工具包括但不限于手机号、银行卡号、APP账号等，主办方和商户有权不予优惠、追回已发放的消费券,并拒绝其今后参加主办方的任何优惠活动；
旅游民宿消费券派发配比将在执行过程中根据实际效果适时调整；
用户参与活动即视为理解并同意本活动细则。若用户在参与活动期间遇到任何疑问，可向微邮惠商圈客服或小邮美宿客服反映，我们将积极协调解决。'''
        return Response({'data': data, "description": description}, status=status.HTTP_200_OK)

    def five_nineteen_retrieve(self, request):
        user = self.request.iser
        if user.is_mobile != 1:
            return Response({'error': '请先完成手机号绑定'}, status=status.HTTP_400_BAD_REQUEST)
        activity_id = self.request.data.get('activity_id', None)
        datetime_now = datetime.datetime.now()
        if activity_id not in [""]:
            return Response({'error': '无效活动'}, status=status.HTTP_400_BAD_REQUEST)
        activity = AliDiscountCoupon.objects.get(template_id=activity_id)
        if activity.publish_start_time > datetime_now:
            return Response({'error': '活动尚未开始'}, status=status.HTTP_400_BAD_REQUEST)
        if activity.publish_end_time < datetime_now:
            return Response({'error': '活动已抢完'}, status=status.HTTP_400_BAD_REQUEST)
        if activity.remain_number <= 0:
            return Response({'error': '活动已抢完'}, status=status.HTTP_400_BAD_REQUEST)
        check_coupon = AliDiscountCouponInfo.objects.filter(customeruservice_id=user.id, alidiscountcoupon_id=activity.id)
        if check_coupon:
            return Response({'error': '不可重复领取'}, status=status.HTTP_400_BAD_REQUEST)
        activity_id = activity.id
        while True:
            activity = AliDiscountCoupon.objects.get(id=activity_id)
            activity_origin_send_count = activity.send_count
            activity_origin_remain_number = activity.remain_number
            activity_new_send_count = activity_origin_send_count + 1
            activity_new_remain_number = activity_origin_remain_number - 1
            result = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(
                send_count=activity_new_send_count,
                remain_number=activity_new_remain_number
            )
            if result == 0:
                continue
            break
        out_biz_no = f'{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}{"%07d" % user.id}'
        appid = settings.CUSTOMER_APP_ID_WYH
        openid = user.wyh_openid
        if activity.platform_id == 13:
            distribute_channel = Channel.objects.get(id=13)
        else:
            distribute_channel = Channel.objects.get(id=9)
        data_json = {
            "stock_id": activity.template_id,
            "out_request_no": out_biz_no,
            "appid": appid,
            "stock_creator_mchid": activity.platform.mchid
        }
        data_dict = favor_distributed_coupons_sichun(data_json, openid, distribute_channel)
        if 'code' in data_dict:
            x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
            if x_forwarded_for:
                ip = x_forwarded_for.split(',')[0]
            else:
                ip = request.META.get('REMOTE_ADDR')
            logger.error(f'{str(data_dict)},{ip}')
            while True:
                activity = AliDiscountCoupon.objects.get(id=activity_id)
                activity_origin_send_count = activity.send_count
                activity_origin_remain_number = activity.remain_number
                activity_new_send_count = activity_origin_send_count - 1
                activity_new_remain_number = activity_origin_remain_number + 1
                result1 = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(
                    send_count=activity_new_send_count,
                    remain_number=activity_new_remain_number
                )
                if result1 == 0:
                    continue
                break
            return Response({'error': data_dict['message']}, status=status.HTTP_400_BAD_REQUEST)
        coupon_id = data_dict['coupon_id']
        result = favor_query_coupons_sichun(coupon_id, openid, appid, distribute_channel)
        data = {
            'alidiscountcoupon_id': activity.id,
            'voucher_id': coupon_id,
            'user_id': openid,
            'appid': appid,
            'template_id': result['stock_id'],
            'gmt_active': result['available_begin_time'].replace('T', ' ').replace('+08:00', ''),
            'gmt_expired': result['available_end_time'].replace('T', ' ').replace('+08:00', ''),
            'total_amount': result['normal_coupon_information']['coupon_amount'] / 100,
            'gmt_create': datetime.datetime.now(),
            'available_amount': result['normal_coupon_information']['coupon_amount'] / 100,
            'name': result['coupon_name'],
            'out_biz_no': out_biz_no,
            'customeruservice_id': user.id,
            'gmt_distributed': datetime.datetime.now(),
            'mobile': user.mobile,
            'coupon_channel': activity.coupon_channel
        }
        voucherinfo, create = AliDiscountCouponInfo.objects.get_or_create(defaults=data, voucher_id=coupon_id)
        if create:
            return Response({'success': '领取成功', 'coupon_id': voucherinfo.id}, status=status.HTTP_200_OK)
        else:
            return Response({'error': '已经领取过了'}, status=status.HTTP_400_BAD_REQUEST)

    def allow_merchant(self, request):
        alidiscountcoupon_id = self.request.query_params.get('alidiscountcoupon_id', None)
        longitude = self.request.query_params.get('longitude', None)
        latitude = self.request.query_params.get('latitude', None)
        search = self.request.query_params.get('search', None)
        try:
            alidiscountcoupon = AliDiscountCoupon.objects.get(id=alidiscountcoupon_id)
        except:
            return Response({"counts": 0, "lists": [], "page": 1, "pages": 1, "pagesize": 10}, status=status.HTTP_200_OK)
        queryset = Merchant.objects.filter(alidiscountcouponmerchant__alidiscountcoupon_id=alidiscountcoupon_id).distinct()
        if search:
            queryset = queryset.filter(Q(wyfMerchantID__contains=search) | Q(name__contains=search))
        if not all([longitude, latitude]):
            pass
        else:
            gcd_formula = "6371 * acos(least(greatest(cos(radians(%s)) * cos(radians(latitude)) * cos(radians(longitude) - radians(%s)) + sin(radians(%s)) * sin(radians(latitude)) , -1), 1))"
            sql = RawSQL(gcd_formula, (latitude, longitude, latitude))
            queryset = queryset.annotate(distance=sql).order_by(F('distance').asc(nulls_last=True))
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = MerchantListModelSerializer(page, many=True, context={'longitude': longitude, 'latitude': latitude})
            return self.get_paginated_response(serializer.data)
        serializer = MerchantListModelSerializer(queryset, many=True, context={'longitude': longitude, 'latitude': latitude})
        return Response(serializer.data)

    def allow_merchant_map(self, request):
        # alidiscountcoupon_id = self.request.query_params.get('alidiscountcoupon_id', None)
        # longitude = self.request.query_params.get('longitude', None)
        # latitude = self.request.query_params.get('latitude', None)
        # if not alidiscountcoupon_id:
        #     return Response({'error': '缺少必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        # try:
        #     alidiscountcoupon = AliDiscountCoupon.objects.get(id=alidiscountcoupon_id)
        # except:
        #     return Response({"count": 0, "merchant_list": [], "max_count": 0, "longitude": longitude, "latitude": latitude}, status=status.HTTP_200_OK)
        # search = self.request.query_params.get('search', None)
        # distance = self.request.query_params.get('distance', 5000)
        # distance = int(distance) / 1000
        # user = self.request.iser
        # if not all([longitude, latitude]):
        #     return Response({'error': '须上传当前位置经纬度'}, status=status.HTTP_400_BAD_REQUEST)
        # # activity = AliDiscountCoupon.objects.get(id=alidiscountcoupon_id)
        # queryset = Merchant.objects.filter(alidiscountcouponmerchant__alidiscountcoupon_id=alidiscountcoupon_id, latitude__isnull=False).distinct()
        # response_data = {}
        # response_data['max_count'] = len(queryset)
        # response_data['count'] = len(queryset)
        # # response_data['activity_info'] = AliDiscountCouponMapModelSerializer(activity, context={'user': user}).data
        # response_data['longitude'] = longitude
        # response_data['latitude'] = latitude
        # if search:
        #     queryset = queryset.filter(Q(short_name__contains=search) | Q(name__contains=search))
        #     response_data['count'] = len(queryset)
        # gcd_formula = "6371 * acos(least(greatest(cos(radians(%s)) * cos(radians(latitude)) * cos(radians(longitude) - radians(%s)) + sin(radians(%s)) * sin(radians(latitude)) , -1), 1))"
        # sql = RawSQL(gcd_formula, (latitude, longitude, latitude))
        # queryset = queryset.annotate(distance=sql).filter(distance__lt=distance).order_by(F('distance').asc(nulls_last=True))
        # if queryset:
        #     first_quert = queryset.first()
        #     response_data['longitude'] = first_quert.longitude
        #     response_data['latitude'] = first_quert.latitude
        # # queryset = queryset.annotate(distance=sql).filter(distance__lt=distance).order_by(F('distance').asc(nulls_last=True))
        # serializer = MerchantListModelSerializer(queryset, many=True, context={'longitude': longitude, 'latitude': latitude})
        # response_data['merchant_list'] = serializer.data
        # return Response(response_data, status=status.HTTP_200_OK)

        # user = self.request.iser
        longitude = self.request.query_params.get('longitude', '')
        latitude = self.request.query_params.get('latitude', '')
        distance = self.request.query_params.get('distance', 2000)
        search = self.request.query_params.get('search', None)
        alidiscountcoupon_id = self.request.query_params.get('alidiscountcoupon_id', None)
        try:
            distance = int(distance)
            distance = distance * 1.5
            if distance > 50000:
                return Response({'error': '搜索距离不能大于50公里'}, status=status.HTTP_400_BAD_REQUEST)
            distance = distance / 1000
        except:
            return Response({'error': '距离参数格式有误'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            alidiscountcoupon = AliDiscountCoupon.objects.get(id=alidiscountcoupon_id)
        except:
            return Response({"count": 0, "merchant_list": [], "max_count": 0, "longitude": longitude, "latitude": latitude}, status=status.HTTP_200_OK)
        if not all([latitude, longitude]):
            return Response({'error': '请上传定位经纬度'}, status=status.HTTP_400_BAD_REQUEST)
        conn = pymysql.connect(host=settings.DATABASES['default']['HOST'],
                               port=settings.DATABASES['default']['PORT'],
                               database=settings.DATABASES['default']['NAME'],
                               user=settings.DATABASES['default']['USER'],
                               password=settings.DATABASES['default']['PASSWORD'])
        cursor = conn.cursor(cursor=pymysql.cursors.SSDictCursor)
        if search:
            condition = f' AND (name LIKE "%{search}%" OR wyfMerchantID LIKE "%{search}%")'
        else:
            condition = ''
        sql = f'SELECT COUNT(*) AS max_count FROM tb_ali_discount_coupon_merchant WHERE alidiscountcoupon_id={alidiscountcoupon_id};'
        cursor.execute(sql)
        max_count = cursor.fetchone()['max_count']
        sql = f'''SELECT id,name,store_address,longitude,latitude,store_header_copy,managermobile,store_logo_copy,short_name,open_work_time,close_work_time,(6371 * acos(cos(radians({latitude})) * cos(radians(latitude)) * cos( radians(longitude) - radians({longitude})) + sin(radians({latitude})) * sin(radians(latitude)))) AS distance FROM tb_merchant WHERE id IN (SELECT merchant_id FROM tb_ali_discount_coupon_merchant WHERE alidiscountcoupon_id={alidiscountcoupon_id}) AND latitude IS NOT NULL{condition} HAVING distance<={distance};'''
        try:
            cursor.execute(sql)
            rows = cursor.fetchall()
        finally:
            cursor.close()
            conn.close()
        for row in rows:
            distance = row['distance']
            if distance < 1:
                row['distance'] = f'{int(distance * 1000)} m'
            else:
                row['distance'] = f'{Decimal(str(distance)).quantize(Decimal("0.00"))} km'
            row['store_header_copy'] = f'https://circle.sutpay.cn/{row["store_header_copy"]}'
            row['store_logo_copy'] = f'https://circle.sutpay.cn/{row["store_logo_copy"]}'
        if rows:
            longitude = rows[0]['longitude']
            latitude = rows[0]['latitude']
        response_data = {}
        response_data['max_count'] = max_count
        response_data['count'] = len(rows)
        response_data['merchant_list'] = rows
        response_data['longitude'] = longitude
        response_data['latitude'] = latitude
        return Response(response_data, status=status.HTTP_200_OK)


class LevelModelViewSet(ModelViewSet):

    serializer_class = LevelModelSerializer
    pagination_class = MyPage
    filter_backends = (filters.SearchFilter, DjangoFilterBackend)
    search_fields = ('name', )
    filter_class = LevelFilter

    def get_queryset(self):
        longitude = self.request.query_params.get('longitude', None)
        latitude = self.request.query_params.get('latitude', None)
        distance = self.request.query_params.get('distance', None)
        goods_id = self.request.query_params.get('goods_id', None)
        city_id = self.request.query_params.get('city_id', None)
        level_id = self.request.query_params.get('level_id', None)
        if not all([longitude, latitude]):
            queryset = Level.objects.filter()
        else:
            gcd_formula = "6371 * acos(least(greatest(cos(radians(%s)) * cos(radians(latitude)) * cos(radians(longitude) - radians(%s)) + sin(radians(%s)) * sin(radians(latitude)) , -1), 1))"
            sql = RawSQL(gcd_formula, (latitude, longitude, latitude))
            queryset = Level.objects.filter().annotate(distance=sql).order_by('distance')
            if distance:
                distance = int(distance) / 1000
                queryset = queryset.filter(distance__lt=distance)
        if goods_id:
            queryset = queryset.filter(launchedgoods__stock__gt=0, launchedgoods__is_launched=1, launchedgoods__goods_id=goods_id).distinct()
        if level_id:
            queryset = queryset.filter(id=level_id)
        return queryset

    def get_serializer_context(self):
        longitude = self.request.query_params.get('longitude', None)
        latitude = self.request.query_params.get('latitude', None)
        return {'longitude': longitude, 'latitude': latitude}

    def activity_city(self, request):
        queryset = Level.objects.exclude(id=35013017).filter(level=2, prov_id=7330)
        data = []
        for query in queryset:
            dic1 = {}
            dic1['name'] = query.name.replace('市分公司', '')
            dic1['id'] = query.id
            data.append(dic1)
        return Response(data, status=status.HTTP_200_OK)

    def list(self, request, *args, **kwargs):
        page1 = self.request.query_params.get('page', '1')
        search = self.request.query_params.get('search', None)
        goods_id = self.request.query_params.get('goods_id', None)
        queryset = self.filter_queryset(self.get_queryset())
        page = self.paginate_queryset(queryset)
        level_id = self.request.query_params.get('level_id', None)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            if goods_id:
                # goods = Goods.objects.filter(id=goods_id, stock__gt=0).first()
                goods = LaunchedGoods.objects.filter(goods_id=goods_id, stock__gt=0, level_id__isnull=True, is_launched=1).first()
                if goods and page1 == '1' and not search and not level_id:
                    response = self.get_paginated_response(serializer.data).data
                    response['lists'].insert(0, {
                        'id': 'X',
                        'name': goods.goods.merchant.store_address,
                        'longitude': 'X',
                        'latitude': 'X',
                        'address': 'X',
                        'distance': 'X',
                        'telephone': 'X',
                        'city_id': 'X',
                        'work_time': 'X',
                    })
                    response['counts'] += 1
                    return Response(response, status=status.HTTP_200_OK)
            return self.get_paginated_response(serializer.data)
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)


class OrderInfoModelViewSet(ModelViewSet):
    '''订单'''

    pagination_class = MyPage
    filter_backends = (filters.SearchFilter, DjangoFilterBackend)
    search_fields = ('ordergoods__merchant__name', 'ordergoods__goods__name')
    filter_class = OrderInfoFilter

    def get_serializer_class(self):
        if self.action == 'list':
            return OrderInfoListModelSerializer
        else:
            return OrderInfoRetrieveModelSerializer

    def get_queryset(self):
        user = self.request.iser
        queryset = OrderInfo.objects.filter(customeruservice_id=user.id).order_by('-create_time', 'state')
        return queryset

    def create(self, request, *args, **kwargs):
        user = self.request.iser
        goods_id = self.request.data.get('goods_id', None)
        count = self.request.data.get('count', None)
        voucher_id = self.request.data.get('voucher_id', None)
        name = self.request.data.get('name', None)
        identity = self.request.data.get('identity', None)
        check_identity = self.request.data.get('check_identity', None)
        level_id = self.request.data.get('level_id', None)
        reserved_mobile = self.request.data.get('reserved_mobile', None)
        point_array = self.request.data.get('point_array', None)
        address_id = self.request.data.get('address_id', None)
        buy_type = self.request.data.get('buy_type', None)
        account = self.request.data.get('account', None)
        is_group = self.request.data.get('is_group', None)
        date_now = datetime.datetime.now()
        if level_id == 'X':
            level_id = None
        if all([goods_id, count]) is False:
            return Response({'error': '缺少必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            count = int(count)
        except:
            return Response({'error': '购买商品数量参数有误'}, status=status.HTTP_400_BAD_REQUEST)
        if count <= 0:
            return Response({'error': '购买商品数量参数有误'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            goods = Goods.objects.get(id=goods_id)
        except:
            return Response({'error': '无效商品id'}, status=status.HTTP_400_BAD_REQUEST)
        if goods.order_type == 2:
            if not all([name, identity, check_identity]):
                return Response({'error': '该下单商品需要提供收款信息'}, status=status.HTTP_400_BAD_REQUEST)
            if identity != check_identity:
                return Response({'error': '两次输入收款信息不一致'}, status=status.HTTP_400_BAD_REQUEST)
            order_type = goods.order_type
        elif goods.order_type in [1, 3]:
            if not reserved_mobile:
                return Response({'error': '请填写预留手机号'}, status=status.HTTP_400_BAD_REQUEST)
            if not re.match(r'^1[3-9]\d{9}$', reserved_mobile):
                return Response({"error": "您输入的手机号格式不正确"}, status=status.HTTP_400_BAD_REQUEST)
            order_type = goods.order_type
        elif goods.order_type == 5:
            if not address_id:
                return Response({'error': '请上传配送信息'}, status=status.HTTP_400_BAD_REQUEST)
            address = CustomerUserViceAddress.objects.filter(customeruservice_id=user.id, id=address_id, is_deleted=0).first()
            if not address:
                return Response({'error': '无效配送信息'}, status=status.HTTP_400_BAD_REQUEST)
            order_type = goods.order_type
        elif goods.order_type == 6:
            if str(buy_type) == '1':
                if not reserved_mobile:
                    return Response({'error': '请填写预留手机号'}, status=status.HTTP_400_BAD_REQUEST)
                if not re.match(r'^1[3-9]\d{9}$', reserved_mobile):
                    return Response({"error": "您输入的手机号格式不正确"}, status=status.HTTP_400_BAD_REQUEST)
            elif str(buy_type) == '5':
                if not address_id:
                    return Response({'error': '请上传配送信息'}, status=status.HTTP_400_BAD_REQUEST)
                address = CustomerUserViceAddress.objects.filter(customeruservice_id=user.id, id=address_id, is_deleted=0).first()
                if not address:
                    return Response({'error': '无效配送信息'}, status=status.HTTP_400_BAD_REQUEST)
            else:
                return Response({'error': '请选择购买方式'}, status=status.HTTP_400_BAD_REQUEST)
            order_type = buy_type
        else:
            order_type = goods.order_type
        if is_group:
            if goods.is_group != 1:
                return Response({'error': '当前商品不支持拼团'}, status=status.HTTP_400_BAD_REQUEST)
            if account:
                group = OrderInfoGROUP.objects.filter(account=account).first()
                if not group:
                    return Response({'error': '无效拼团订单'}, status=status.HTTP_400_BAD_REQUEST)
                if group.group_status != 1:
                    return Response({'error': '拼团订单已结束'}, status=status.HTTP_400_BAD_REQUEST)
                check_group_order = OrderInfo.objects.filter(group_id=group.id).exclude(state=13)
                if len(check_group_order) >= group.group_order_num:
                    return Response({'error': '拼团已达到达到上限'}, status=status.HTTP_400_BAD_REQUEST)
                main_order = OrderInfo.objects.get(id=group.order_id)
                if main_order.state != 15:
                    return Response({'error': '拼团订单状态有误'}, status=status.HTTP_400_BAD_REQUEST)
                for group_order in check_group_order:
                    if group_order.customeruservice_id == user.id:
                        return Response({'error': '已参与拼团,不能重复参与'}, status=status.HTTP_400_BAD_REQUEST)
            else:
                defaults = {}
                defaults['customeruservice_id'] = user.id
                defaults['goods_id'] = goods_id
                defaults['account'] = random_str(10)
                if goods.group_limit_type == 1:
                    expired_time = date_now + datetime.timedelta(days=goods.group_limit_time)
                else:
                    expired_time = date_now + datetime.timedelta(hours=goods.group_limit_time)
                defaults['expired_time'] = expired_time
                defaults['group_order_num'] = goods.group_order_num
                group, create = OrderInfoGROUP.objects.get_or_create(defaults=defaults, account=account)
            order_type = 7
            goods_price = goods.group_price
        else:
            goods_price = goods.price
            group = None
        if level_id:
            try:
                level = Level.objects.get(id=level_id)
                launchedgoods = LaunchedGoods.objects.filter(goods_id=goods_id, level_id=level_id).first()
                if not launchedgoods:
                    return Response({'error': '选择网点商品库存不足,请重新选择'}, status=status.HTTP_400_BAD_REQUEST)
            except:
                return Response({'error': '无效自提网点id'}, status=status.HTTP_400_BAD_REQUEST)
        else:
            try:
                launchedgoods = LaunchedGoods.objects.filter(goods_id=goods_id, level_id__isnull=True).first()
                if not launchedgoods:
                    return Response({'error': '选择网点商品库存不足,请重新选择'}, status=status.HTTP_400_BAD_REQUEST)
            except:
                return Response({'error': '无效自提网点id'}, status=status.HTTP_400_BAD_REQUEST)
        launchedgoods_id = launchedgoods.id
        try:
            count = int(count)
        except Exception:
            return Response({'error': '参数count有误'}, status=status.HTTP_400_BAD_REQUEST)
        if goods.is_buymore == 0 and count != 1:
            return Response({'error': '当前商品不允许同时购买多件'}, status=status.HTTP_400_BAD_REQUEST)
        if goods.limit_by_user_count:
            buy_count = OrderGoods.objects.exclude(order__state=13).filter(order__customer_user_id=user.id, goods_id=goods.id).aggregate(Sum('count'))['count__sum']
            if buy_count:
                if buy_count >= goods.limit_by_user_count:
                    return Response({'error': '当前商品超出限购数量'}, status=status.HTTP_400_BAD_REQUEST)
        order_id = timezone.now().strftime('%Y%m%d%H%M%S') + ('%06d' % randint(0, 999999)) + ('%09d' % user.id)
        if voucher_id:
            try:
                alidiscounponinfo = AliDiscountCouponInfo.objects.get(voucher_id=voucher_id, alidiscountcoupon__coupon_channel=3, customeruservice_id=user.id, status=1, gmt_expired__gte=datetime.datetime.now(), gmt_active__lte=datetime.datetime.now())
            except:
                return Response({'error': '优惠券选择有误,请返回重新选择'}, status=status.HTTP_400_BAD_REQUEST)
            alidiscountcoupon = alidiscounponinfo.alidiscountcoupon
            if alidiscountcoupon.coupon_type == 6:
                payable_amount = ((count-1) * goods_price)
            else:
                payable_amount = (count * goods_price) - alidiscounponinfo.total_amount
        else:
            payable_amount = (count * goods_price)
            alidiscounponinfo = None
        if point_array:
            try:
                point_set = ActivityData.objects.filter(id__in=point_array, state__in=[2, 3], customeruservice_id=user.id, activity__available_begin_time__lte=date_now, activity__available_end_time__gte=date_now).order_by('activity__available_end_time')
            except:
                return Response({'error': '优惠券选择有误,请返回重新选择'}, status=status.HTTP_400_BAD_REQUEST)
        else:
            point_set = None
        # 显示的开启一个事务
        with transaction.atomic():
            # 创建事务保存点
            save_id = transaction.savepoint()

            # 暴力回滚
            try:
                # 保存订单基本信息OrderInfo(一)
                order_data = {}
                order_data['order_id'] = order_id
                order_data['customeruservice_id'] = user.id
                order_data['create_time'] = date_now
                order_data['total_count'] = count
                order_data['total_price'] = (count * goods_price)
                order_data['state'] = 1
                order_data['merchant_id'] = goods.merchant_id
                order_data['payable_amount'] = payable_amount
                order_data['reserved_mobile'] = reserved_mobile
                order_data['order_type'] = order_type
                order_data['order_species'] = 2
                if level_id:
                    order_data['level_id'] = level_id
                else:
                    order_data['level_id'] = level_id
                if group:
                    order_data['group_id'] = group.id
                order = OrderInfo.objects.create(**order_data)
                if group and not group.order_id:
                    group.order_id = order.id
                    group.save()
                if order_type == 5:
                    orderaddress_data = {}
                    orderaddress_data['order_id'] = order.id
                    orderaddress_data['receiver'] = address.receiver
                    orderaddress_data['province'] = address.province
                    orderaddress_data['city'] = address.city
                    orderaddress_data['district'] = address.district
                    orderaddress_data['place'] = address.place
                    orderaddress_data['mobile'] = address.mobile
                    orderaddress_data['longitude'] = address.longitude
                    orderaddress_data['latitude'] = address.latitude
                    OrderAddress.objects.get_or_create(defaults=orderaddress_data, order_id=order.id)
                if alidiscounponinfo:
                    alidiscounponinfo.status = 8
                    alidiscounponinfo.order_id = order.id
                    alidiscounponinfo.save()
                if point_set:
                    select_point__sum = payable_amount * 100
                    point = Decimal('0')
                    for activitydata in point_set:
                        if select_point__sum <= 0:
                            break
                        remain_point = activitydata.remain_point
                        if remain_point <= select_point__sum:
                            activitydata.state = 6
                            activitydata.remain_point = 0
                            activitydata.save()
                            user.point -= remain_point
                            user.save()
                            out_pointrecord_data = {}
                            out_pointrecord_data['customer_user_id'] = user.id
                            out_pointrecord_data['create_time'] = date_now
                            out_pointrecord_data['operate_type'] = 2
                            out_pointrecord_data['business_type'] = 2
                            out_pointrecord_data['point'] = remain_point
                            out_pointrecord_data['point_balance'] = user.point
                            out_pointrecord_data['remain_point'] = 0
                            out_pointrecord_data['order_id'] = order.id
                            out_pointrecord_data['activity_data_id'] = activitydata.id
                            PointRecord.objects.create(**out_pointrecord_data)
                            payable_amount -= (remain_point / 100)
                            point += remain_point
                        else:
                            activitydata.state = 3
                            activitydata.remain_point = remain_point - select_point__sum
                            activitydata.save()
                            user.point -= select_point__sum
                            user.save()
                            out_pointrecord_data = {}
                            out_pointrecord_data['customer_user_id'] = user.id
                            out_pointrecord_data['create_time'] = date_now
                            out_pointrecord_data['operate_type'] = 2
                            out_pointrecord_data['business_type'] = 2
                            out_pointrecord_data['point'] = select_point__sum
                            out_pointrecord_data['point_balance'] = user.point
                            out_pointrecord_data['remain_point'] = activitydata.remain_point
                            out_pointrecord_data['order_id'] = order.id
                            out_pointrecord_data['activity_data_id'] = activitydata.id
                            PointRecord.objects.create(**out_pointrecord_data)
                            payable_amount -= (select_point__sum / 100)
                            point += select_point__sum
                        select_point__sum -= remain_point
                    order.total_point = point
                    order.payable_amount = payable_amount
                    order.save()
                while True:
                    goods = Goods.objects.get(id=goods_id)
                    origin_stock = goods.stock
                    origin_sales = goods.sales
                    origin_remain_stock = goods.remain_stock
                    launchedgoods = LaunchedGoods.objects.get(id=launchedgoods_id)
                    launched_origin_stock = launchedgoods.stock
                    launched_origin_sales = launchedgoods.sales
                    if count > launched_origin_stock:
                        transaction.savepoint_rollback(save_id)
                        return Response({'error': '库存不足'}, status=status.HTTP_400_BAD_REQUEST)
                    launched_new_stock = launched_origin_stock - count
                    launched_new_sales = launched_origin_sales + count
                    new_sales = origin_sales + count
                    new_remain_stock = origin_remain_stock - count
                    if not launchedgoods.level_id:
                        new_stock = origin_stock - count
                    else:
                        new_stock = origin_stock
                    launched_result = LaunchedGoods.objects.filter(id=launchedgoods_id, stock=launched_origin_stock).update(stock=launched_new_stock, sales=launched_new_sales)
                    result = Goods.objects.filter(id=goods_id).update(sales=new_sales, remain_stock=new_remain_stock, stock=new_stock)
                    if launched_result == 0:
                        continue
                    break
                OrderGoods.objects.create(
                    order=order,
                    goods=goods,
                    count=count,
                    price=goods_price,
                    merchant_id=goods.merchant_id,
                    launched_goods_id=launchedgoods_id
                )
                if goods.category_id == 3:
                    for i in range(count):
                        out_biz_no = f'100005{str(date_now).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}'
                        order_fund_trans_data = {}
                        order_fund_trans_data['out_biz_no'] = out_biz_no
                        order_fund_trans_data['exchange_amount'] = goods.exchange_amount
                        order_fund_trans_data['order_title'] = '支付宝积分网点兑活动'
                        if not all([name, identity, check_identity]):
                            order_fund_trans_data['identity'] = user.ali_user_id
                            order_fund_trans_data['identity_type'] = 1
                        else:
                            order_fund_trans_data['identity'] = identity
                            order_fund_trans_data['identity_type'] = 2
                            order_fund_trans_data['name'] = name
                        order_fund_trans_data['remark'] = ''
                        order_fund_trans_data['goods_id'] = goods.id
                        order_fund_trans_data['order_id'] = order.id
                        OrderFundTrans.objects.get_or_create(defaults=order_fund_trans_data, out_biz_no=out_biz_no)
                if goods.merchant_id in [1827370, 1166424]:
                    sd_order_data = {}
                    sd_order_data['order_id'] = order.id
                    sd_order_data['outTradeNo'] = order.order_id
                    formCode = goods.specifications
                    sd_order_data['formCode'] = formCode
                    sd_order_data['formCode'] = formCode
                    sd_order, create = OrderSchengle.objects.get_or_create(defaults=sd_order_data, order_id=order.id)
            except Exception as e:
                logger.error(e)
                # 事务回滚
                transaction.savepoint_rollback(save_id)
                return Response({'error': '下单失败'}, status=status.HTTP_400_BAD_REQUEST)
        eta = datetime.datetime.utcnow() + datetime.timedelta(minutes=15)
        cancel_over_time_order.apply_async(({'order_id': order.id},), eta=eta)
        transaction.savepoint_commit(save_id)
        add_orderinfo_index.delay({'id': order.id})
        return Response({'success': '下单成功', 'order_id': order.id}, status=status.HTTP_200_OK)

    def partial_update(self, request, *args, **kwargs):
        instance = self.get_object()
        user = self.request.iser
        HTTP_USER_AGENT = self.request.environ['HTTP_USER_AGENT']
        if instance.state != 1:
            return Response({'error': '订单状态错误'}, status=status.HTTP_400_BAD_REQUEST)
        if instance.order_type == 7:
            group = instance.group
            if group.group_status not in [1, 0]:
                return Response({'error': '拼团已结束'}, status=status.HTTP_400_BAD_REQUEST)
        if instance.payable_amount:
            if 'WeChat' in HTTP_USER_AGENT or 'MicroMessenger' in HTTP_USER_AGENT:
                # is_new = self.request.is_new
                # if is_new:
                #     appid = settings.CUSTOMER_APP_ID_NEW
                #     openid = user.new_openid
                # else:
                if instance.merchant.is_mall == 2:
                    if instance.merchant.is_profit_share == 2:
                        # order_id = timezone.now().strftime('%Y%m%d%H%M%S') + ('%06d' % randint(0, 999999)) + ('%09d' % user.id)
                        appid = settings.CUSTOMER_APP_ID_WYH
                        openid = user.wyh_openid
                        data_json = {}
                        data_json['program_id'] = '202316837141378884'
                        data_json['shop_id'] = instance.merchant.wyfMerchantID
                        data_json['appid'] = appid
                        data_json['device'] = instance.merchant.device
                        data_json['order_id'] = instance.order_id
                        data_json['notify_url'] = 'https://api.sutpay.com/cpay/cmf_result/'
                        data_json['money'] = str(instance.payable_amount)
                        data_json['openid'] = openid
                        data_json['order_type'] = 'weixin'
                        data_json['ver'] = '3.0'
                        goods = instance.ordergoods_set.all().first()
                        if goods.goods.goods_tag:
                            data_json['goods_tag'] = goods.goods.goods_tag
                        data_dict = cmf_pay_transactions_jsapi(data_json)
                        if 'error_msg' in data_dict:
                            return Response({'error': data_dict['error_msg']}, status=status.HTTP_400_BAD_REQUEST)
                        instance.orderNum = data_dict.pop('out_trade_no', '')
                        instance.pay_type = 2
                        # instance.order_id = order_id
                        instance.save()
                        data_dict['order_id'] = instance.id
                        data_dict['code'] = '0'
                        return Response(data_dict, status=status.HTTP_200_OK)
                    # order_id = timezone.now().strftime('%Y%m%d%H%M%S') + ('%06d' % randint(0, 999999)) + ('%09d' % user.id)
                    elif instance.merchant.is_profit_share == 4:
                        appid = settings.CUSTOMER_APP_ID_WYH
                        openid = user.wyh_openid
                        data_json = {}
                        data_json['program_id'] = '202316837141378884'
                        data_json['shop_id'] = instance.merchant.wyfMerchantID
                        data_json['appid'] = appid
                        data_json['device'] = instance.merchant.device
                        data_json['order_id'] = instance.order_id
                        data_json['notify_url'] = 'https://api.sutpay.com/cpay/cmf_result/'
                        data_json['money'] = str(instance.payable_amount)
                        data_json['openid'] = openid
                        data_json['order_type'] = 'weixin'
                        data_json['ver'] = '3.0'
                        goods = instance.ordergoods_set.all().first()
                        if goods.goods.goods_tag:
                            data_json['goods_tag'] = goods.goods.goods_tag
                        data_json['profit_share_type'] = '4'
                        data_dict = cmf_pay_transactions_jsapi(data_json)
                        if 'error_msg' in data_dict:
                            return Response({'error': data_dict['error_msg']}, status=status.HTTP_400_BAD_REQUEST)
                        instance.orderNum = data_dict.pop('out_trade_no', '')
                        instance.pay_type = 2
                        instance.is_profit_sharing = 3
                        # instance.order_id = order_id
                        instance.save()
                        data_dict['order_id'] = instance.id
                        data_dict['code'] = '0'
                        return Response(data_dict, status=status.HTTP_200_OK)
                    elif instance.merchant.is_profit_share == 1:
                        appid = settings.CUSTOMER_APP_ID_WYH
                        openid = user.wyh_openid
                        data_json = {}
                        data_json['program_id'] = '202316837141378884'
                        data_json['shop_id'] = instance.merchant.wyfMerchantID
                        data_json['appid'] = appid
                        data_json['device'] = instance.merchant.device
                        data_json['order_id'] = instance.order_id
                        data_json['notify_url'] = 'https://api.sutpay.com/cpay/cmf_result/'
                        data_json['money'] = str(instance.payable_amount)
                        data_json['openid'] = openid
                        data_json['order_type'] = 'weixin'
                        data_json['ver'] = '3.0'
                        goods = instance.ordergoods_set.all().first()
                        if goods.goods.goods_tag:
                            data_json['goods_tag'] = goods.goods.goods_tag
                        data_json['profit_share_type'] = '2'
                        data_dict = cmf_pay_transactions_jsapi(data_json)
                        if 'error_msg' in data_dict:
                            return Response({'error': data_dict['error_msg']}, status=status.HTTP_400_BAD_REQUEST)
                        instance.orderNum = data_dict.pop('out_trade_no', '')
                        instance.pay_type = 2
                        instance.is_profit_sharing = 1
                        # instance.order_id = order_id
                        instance.save()
                        data_dict['order_id'] = instance.id
                        data_dict['code'] = '0'
                        return Response(data_dict, status=status.HTTP_200_OK)
                    else:
                        return Response({'error': '商家尚未上架微邮惠商圈'}, status=status.HTTP_400_BAD_REQUEST)
                else:
                    return Response({'error': '商家尚未上架微邮惠商圈'}, status=status.HTTP_400_BAD_REQUEST)
                    appid = settings.CUSTOMER_APP_ID_WYH
                    openid = user.wyh_openid
                    data_json = {}
                    data_json['appid'] = appid
                    data_json['mchid'] = '1486198522'
                    data_json['description'] = instance.ordergoods_set.all().first().goods.name
                    data_json['out_trade_no'] = instance.order_id
                    data_json['notify_url'] = 'https://api.sutpay.com/cpay/wx_result/'
                    data_json['amount'] = {"total": int(instance.payable_amount*100)}
                    data_json['payer'] = {"openid": openid}
                    data_dict = pay_transactions_jsapi(data_json, appid)
                    if 'code' in data_dict:
                        if data_dict['code'] not in ['OUT_TRADE_NO_USED', 'ORDER_NOT_EXIST', 'ORDER_CLOSED', 'INVALID_REQUEST']:
                            return Response({'error': data_dict['message']}, status=status.HTTP_400_BAD_REQUEST)
                        else:
                            order_id = timezone.now().strftime('%Y%m%d%H%M%S') + ('%06d' % randint(0, 999999)) + ('%09d' % user.id)
                            instance.order_id = order_id
                            instance.save()
                            data_json['out_trade_no'] = instance.order_id
                            data_dict = pay_transactions_jsapi(data_json, appid)
                            if 'code' in data_dict:
                                return Response({'error': data_dict['message']}, status=status.HTTP_400_BAD_REQUEST)
                    instance.orderNum = data_dict['package'].replace('prepay_id=', '')
                    instance.pay_type = 2
                    instance.save()
                    data_dict['order_id'] = instance.id
                    data_dict['code'] = '0'
                    return Response(data_dict, status=status.HTTP_200_OK)
            else:
                buyer_id = user.ali_user_id
                out_trade_no = instance.order_id
                total_amount = instance.payable_amount
                alipay_obj = AlipayOpen()
                description = instance.ordergoods_set.all().first().goods.name
                result = json.loads(alipay_obj.tradecreate(out_trade_no, total_amount, buyer_id, description))
                if result['code'] != '10000':
                    if result['sub_code'] != 'ACQ.TRADE_HAS_CLOSE':
                        return Response({'error': result['sub_msg']}, status=status.HTTP_400_BAD_REQUEST)
                    else:
                        order_id = timezone.now().strftime('%Y%m%d%H%M%S') + ('%06d' % randint(0, 999999)) + ('%09d' % user.id)
                        instance.order_id = order_id
                        instance.save()
                        result = json.loads(alipay_obj.tradecreate(order_id, total_amount, buyer_id, description))
                        if result['code'] != '10000':
                            return Response({'error': result['sub_msg']}, status=status.HTTP_400_BAD_REQUEST)
                instance.orderNum = result['trade_no']
                instance.pay_type = 1
                instance.save()
                return Response({'order_id': instance.id, 'trade_no': result['trade_no'], 'code': '0'}, status=status.HTTP_200_OK)
        else:
            orderNum = timezone.now().strftime('%Y%m%d%H%M%S') + ('%06d' % randint(0, 999999)) + ('%08d' % user.id)
            instance.orderNum = orderNum
            if instance.order_type == 1:
                instance.state = 2
            else:
                instance.state = 12
            instance.payment_time = datetime.datetime.now()
            instance.trade_no = orderNum
            instance.realpay_amount = 0
            instance.save()
            ordergoods_set = instance.ordergoods_set.all()
            for ordergoods in ordergoods_set:
                if ordergoods.goods.category_id == 2:
                    goodscoupons_set = GoodsCoupons.objects.filter(goods_id=ordergoods.goods_id, status=0)[:ordergoods.count]
                    for goodscoupons in goodscoupons_set:
                        goodscoupons.order_id = instance.id
                        goodscoupons.status = 1
                        goodscoupons.save()
                elif ordergoods.goods.category_id == 1:
                    for i in range(ordergoods.count):
                        while True:
                            coupons_id = '%16d' % randint(0, 9999999999999999)
                            goodscoupons = GoodsCoupons.objects.filter(coupons_id=coupons_id)
                            if not goodscoupons:
                                break
                        GoodsCoupons.objects.create(
                            coupons_id=coupons_id.replace(' ', ''),
                            status=1,
                            goods_id=ordergoods.goods_id,
                            order_id=instance.id,
                            validity_time=datetime.datetime.now()
                        )
                try:
                    if ordergoods.goods.is_settlement == 1:
                        receipts_time = datetime.datetime.now().strftime('%Y-%m-%d')
                        bill = MerchantBill.objects.filter(receipts_time=receipts_time, merchant_id=ordergoods.merchant_id).first()
                        if not bill:
                            bill_data = {}
                            bill_data['merchant_id'] = ordergoods.merchant_id
                            bill_data['receipts_time'] = receipts_time
                            bill_data['point'] = ordergoods.point
                            bill_data['amount'] = ordergoods.price * ordergoods.count
                            bill_data['payable_amount'] = ordergoods.price + Decimal(int(ordergoods.point)/100)
                            bill, create = MerchantBill.objects.get_or_create(defaults=bill_data, receipts_time=receipts_time, merchant_id=ordergoods.merchant_id)
                        else:
                            bill.point = bill.point + ordergoods.point
                            bill.amount = bill.amount + (ordergoods.price * ordergoods.count)
                            bill.payable_amount = bill.payable_amount + ordergoods.point + (ordergoods.price * ordergoods.count)
                            bill.save()
                        instance.bill_id = bill.id
                        instance.save()
                except:
                    pass
            try:
                orderfundtrans_set = instance.orderfundtrans_set.all().filter(status=1)
                for orderfundtrans in orderfundtrans_set:
                    alipay_obj = AlipayOpen()
                    trans_amount = str(orderfundtrans.exchange_amount)
                    order_title = orderfundtrans.order_title
                    out_biz_no = orderfundtrans.out_biz_no
                    identity = orderfundtrans.identity
                    if orderfundtrans.identity_type == 1:
                        result = json.loads(alipay_obj.transunitransfer_user_id(identity, out_biz_no, trans_amount, order_title))
                    else:
                        name = orderfundtrans.name
                        result = json.loads(alipay_obj.transunitransfer_login_id(identity, name, out_biz_no, trans_amount, order_title))
                    if result['code'] != '10000':
                        orderfundtrans.sub_msg = result['sub_msg']
                        orderfundtrans.status = 4
                        orderfundtrans.save()
                    else:
                        orderfundtrans.ali_order_id = result['order_id']
                        orderfundtrans.pay_fund_order_id = result['pay_fund_order_id']
                        orderfundtrans.trans_date = result['trans_date']
                        orderfundtrans.status = 2
                        orderfundtrans.save()
            except Exception as e:
                pass
            alidiscounponinfo_set = instance.alidiscountcouponinfo_set.all().filter(status=8)
            for voucher in alidiscounponinfo_set:
                activityinfo = voucher.alidiscountcoupon
                activityinfo.use_count += 1
                activityinfo.save()
                voucher.gmt_use = datetime.datetime.now()
                voucher.status = 7
                voucher.save()
                coupon_bill_data = {}
                coupon_bill_data['amount'] = instance.total_price
                coupon_bill_data['voucherinfo_id'] = voucher.id
                coupon_bill_data['biz_type'] = 'V_USE'
                coupon_bill_data['gmt_create'] = datetime.datetime.now()
                coupon_bill_data['status'] = 'S'
                coupon_bill_data['trade_no'] = orderNum
                AliDiscountCouponBillDetails.objects.create(**coupon_bill_data)
                try:
                    alidiscountcoupon_level = voucher.alidiscountcoupon_level
                    alidiscountcoupon_level.use_number += 1
                    alidiscountcoupon_level.p_use_number += 1
                    alidiscountcoupon_level.save()
                    relation_set = alidiscountcoupon_level.child_set.all()
                    for relation in relation_set:
                        parent = relation.parent
                        parent.p_use_number += 1
                        parent.save()
                    voucher_detail_data = {}
                    voucher_detail_data['v_type'] = 'COUPON'
                    voucher_detail_data['voucherId'] = voucher.voucher_id
                    voucher_detail_data['name'] = voucher.name
                    voucher_detail_data['otherContribute'] = instance.total_price
                    voucher_detail_data['merchantContribute'] = 0
                    voucher_detail_data['ali_order_id'] = instance.id
                    voucher_detail_data['amount'] = instance.total_price
                    VoucherDetail.objects.create(**voucher_detail_data)
                except:
                    pass
            return Response({'order_id': instance.id, 'trade_no': '', 'code': '1'}, status=status.HTTP_200_OK)

    def destroy(self, request, *args, **kwargs):
        user = self.request.iser
        instance = self.get_object()
        if instance.state not in [1, 2, 15]:
            return Response({'error': '订单状态错误'}, status=status.HTTP_400_BAD_REQUEST)
        if instance.customeruservice_id != user.id:
            return Response({'error': '你无权限操作'}, status=status.HTTP_400_BAD_REQUEST)
        if instance.state in [2, 15]:
            if instance.merchant_id == 1827370:
                return Response({'error': '当前订单类型不支持退款'}, status=status.HTTP_400_BAD_REQUEST)
            url = 'https://api.gdwxyf.com/api/refund.do'
            datetime_now = datetime.datetime.now()
            order_id = f'{datetime_now.strftime("%Y%m%d%H%M%S")}{"%06d" % randint(0, 999999)}'
            body = {
                "program_id": "202316837141378884",
                "shop_id": instance.merchant.ruiyinxinMerchantID,
                "refund_order_id": order_id,
                "order_id": instance.orderNum
            }
            key = '6715C7D4435343BA0459EAEC2334D81B'
            sign = get_sign(body, key)
            body['sign'] = sign
            response = requests.post(url=url, json=body)
            result = response.json()
            if result['result_code'] == 'success':
                refund_order_data = {}
                refund_order_data['order_id'] = instance.id
                refund_order_data['operator_role'] = 6
                refund_order_data['customeruservice_id'] = user.id
                refund_order_data['refund_order_id'] = order_id
                refund_order_data['refund_transaction_id'] = result['refund_transaction_id']
                refund_order_data['plat_refund_order_id'] = result['plat_refund_order_id']
                refund_order_data['refund_money'] = result['refund_money']
                refund_order_data['refund_procedure_money'] = result['commission']
                refund_order_data['refund_time'] = datetime.datetime.strptime(result['refund_end_time'], '%Y%m%d%H%M%S')
                refund_order_data['remark'] = '消费者取消订单'
                RefundOrderInfo.objects.create(**refund_order_data)
                instance.state = 8
                instance.refund_money = instance.realpay_amount
                instance.out_refund_no = order_id
                instance.refund_id = result['refund_transaction_id']
                instance.cancel_time = datetime.datetime.now()
                instance.save()
                ordergoods_set = instance.ordergoods_set.all()
                for ordergoods in ordergoods_set:
                    goods = ordergoods.goods
                    launched_goods = ordergoods.launched_goods
                    count = ordergoods.count
                    origin_sales = goods.sales
                    origin_remain_stock = goods.remain_stock
                    new_sales = origin_sales - count
                    new_remain_stock = origin_remain_stock + count
                    goods.sales = new_sales
                    goods.remain_stock = new_remain_stock
                    goods.save()
                    if launched_goods:
                        launched_origin_stock = launched_goods.stock
                        launched_origin_sales = launched_goods.sales
                        launched_new_stock = launched_origin_stock + count
                        launched_new_sales = launched_origin_sales - count
                        launched_goods.stock = launched_new_stock
                        launched_goods.sales = launched_new_sales
                        launched_goods.save()
                    else:
                        origin_stock = goods.stock
                        new_stock = origin_stock + count
                        goods.stock = new_stock
                        goods.save()
                return Response({'success': '取消订单成功'}, status=status.HTTP_200_OK)
            else:
                refund_order_data = {}
                refund_order_data['refund_status'] = 2
                refund_order_data['operator_role'] = 6
                refund_order_data['customeruservice_id'] = user.id
                refund_order_data['order_id'] = instance.id
                refund_order_data['return_msg'] = result['error_msg']
                refund_order_data['refund_order_id'] = order_id
                refund_order_data['refund_time'] = datetime_now
                refund_order_data['remark'] = '消费者取消订单'
                refund_order_data['return_msg'] = result["error_msg"]
                RefundOrderInfo.objects.create(**refund_order_data)
                return Response({'error': f'取消订单失败,{result["error_msg"]}'}, status=status.HTTP_400_BAD_REQUEST)
        else:
            ordergoods_set = instance.ordergoods_set.all()
            for ordergoods in ordergoods_set:
                goods = ordergoods.goods
                launched_goods = ordergoods.launched_goods
                count = ordergoods.count
                origin_sales = goods.sales
                origin_remain_stock = goods.remain_stock
                new_sales = origin_sales - count
                new_remain_stock = origin_remain_stock + count
                goods.sales = new_sales
                goods.remain_stock = new_remain_stock
                goods.save()
                if launched_goods:
                    launched_origin_stock = launched_goods.stock
                    launched_origin_sales = launched_goods.sales
                    launched_new_stock = launched_origin_stock + count
                    launched_new_sales = launched_origin_sales - count
                    launched_goods.stock = launched_new_stock
                    launched_goods.sales = launched_new_sales
                    launched_goods.save()
                else:
                    origin_stock = goods.stock
                    new_stock = origin_stock + count
                    goods.stock = new_stock
                    goods.save()
            instance.state = 13
            instance.cancel_time = datetime.datetime.now()
            instance.total_point = 0
            instance.save()
            alidiscounponinfo_set = instance.alidiscountcouponinfo_set.all().filter(status=8).update(status=1, order_id=None)
            try:
                pointrecord_set = instance.pointrecord_set.all()
                for pointrecord in pointrecord_set:
                    activity_data = pointrecord.activity_data
                    activity_data.remain_point += pointrecord.point
                    activity_data.state = 3
                    activity_data.save()
                    user.point += pointrecord.point
                    user.save()
                    in_pointrecord_data = {}
                    in_pointrecord_data['customer_user_id'] = user.id
                    in_pointrecord_data['create_time'] = datetime.datetime.now()
                    in_pointrecord_data['operate_type'] = 1
                    in_pointrecord_data['business_type'] = 4
                    in_pointrecord_data['point'] = pointrecord.point
                    in_pointrecord_data['point_balance'] = user.point
                    in_pointrecord_data['remain_point'] = activity_data.remain_point
                    in_pointrecord_data['activity_data_id'] = activity_data.id
                    in_pointrecord_data['order_id'] = instance.id
                    PointRecord.objects.create(**in_pointrecord_data)
            except:
                pass
            return Response({'success': '取消订单成功'}, status=status.HTTP_200_OK)

    def preferential(self, request):
        user = self.request.iser
        goods_array = self.request.data.get('goods_array', None)
        voucher_id = self.request.data.get('voucher_id', None)
        point_array = self.request.data.get('point_array', None)
        if not goods_array:
            return Response({'error': '缺少商品信息'}, status=status.HTTP_400_BAD_REQUEST)
        goods_id_list = []
        try:
            total_point = Decimal('0')
            total_price = Decimal('0')
            max_price = Decimal('0')
            for goods_data in goods_array:
                goods = Goods.objects.get(id=goods_data['goods_id'])
                if goods.is_use_point == 1:
                    total_point += Decimal(int(goods_data['count'])) * 100 * goods.price
                total_price += Decimal(int(goods_data['count'])) * goods.price
                if goods.price > max_price:
                    max_price = goods.price
                goods_id_list.append(goods.id)
        except:
            return Response({'error': '无效商品id'}, status=status.HTTP_400_BAD_REQUEST)
        point_data = []
        voucher_list = []
        data = {}
        data['referential_price'] = Decimal('0')
        data['point_amount'] = Decimal('0')
        use_count = 0
        try:
            alidiscountcoupon_id_list = list(AliDiscountCouponGoodsAvailable.objects.filter(goods_id__in=goods_id_list).values_list('alidiscountcoupon_id', flat=True))
            alidiscountcouponinfo_set = AliDiscountCouponInfo.objects.filter(alidiscountcoupon__coupon_channel=3, customeruservice_id=user.id, status=1, gmt_expired__gte=datetime.datetime.now(), gmt_active__lte=datetime.datetime.now()).order_by('-total_amount')
            if alidiscountcouponinfo_set:
                total_amount__max = alidiscountcouponinfo_set.filter(alidiscountcoupon_id__in=alidiscountcoupon_id_list).aggregate(Max('total_amount'))['total_amount__max']
                if total_amount__max > max_price:
                    select_alidiscountcouponinfo = alidiscountcouponinfo_set.filter(total_amount=total_amount__max,alidiscountcoupon_id__in=alidiscountcoupon_id_list).first()
                    data['referential_price'] = select_alidiscountcouponinfo.total_amount
                else:
                    select_alidiscountcouponinfo = alidiscountcouponinfo_set.filter(alidiscountcoupon__coupon_type=6,alidiscountcoupon_id__in=alidiscountcoupon_id_list).first()
                    if select_alidiscountcouponinfo:
                        data['referential_price'] = max_price
                    else:
                        select_alidiscountcouponinfo = alidiscountcouponinfo_set.filter(total_amount=total_amount__max,alidiscountcoupon_id__in=alidiscountcoupon_id_list).first()
                        data['referential_price'] = select_alidiscountcouponinfo.total_amount
                if voucher_id:
                    select_alidiscountcouponinfo1 = alidiscountcouponinfo_set.filter(voucher_id=voucher_id).first()
                    if select_alidiscountcouponinfo1:
                        if select_alidiscountcouponinfo1.alidiscountcoupon.coupon_type == 6:
                            data['referential_price'] = max_price
                        else:
                            data['referential_price'] = select_alidiscountcouponinfo1.total_amount
                        a = 1
                    else:
                        a = 0
                else:
                    a = 0
                for alidiscountcouponinfo in alidiscountcouponinfo_set:
                    r_data = {}
                    r_data['activity_name'] = alidiscountcouponinfo.alidiscountcoupon.activity_name
                    r_data['gmt_expired'] = alidiscountcouponinfo.gmt_expired.strftime('%Y-%m-%d %H:%M:%S')
                    r_data['floor_amount'] = alidiscountcouponinfo.alidiscountcoupon.floor_amount
                    coupon_type = alidiscountcouponinfo.alidiscountcoupon.coupon_type
                    if coupon_type == 9:
                        r_data['amount'] = alidiscountcouponinfo.total_amount
                    else:
                        r_data['amount'] = max_price
                    r_data['coupon_type'] = coupon_type
                    r_data['coupon_type_str'] = alidiscountcouponinfo.alidiscountcoupon.get_coupon_type_display()
                    r_data['voucher_id'] = alidiscountcouponinfo.voucher_id
                    if alidiscountcouponinfo.alidiscountcoupon_id in alidiscountcoupon_id_list:
                        r_data['is_choose'] = 1
                        use_count += 1
                    else:
                        r_data['is_choose'] = 0
                        r_data['reason'] = '限定商品可用'
                    if a == 1:
                        if alidiscountcouponinfo.voucher_id == voucher_id:
                            r_data['choose'] = 1
                        else:
                            r_data['choose'] = 0
                    else:
                        if alidiscountcouponinfo.id == select_alidiscountcouponinfo.id:
                            r_data['choose'] = 1
                        else:
                            r_data['choose'] = 0
                    if alidiscountcouponinfo.id == select_alidiscountcouponinfo.id:
                        voucher_list.insert(0, r_data)
                    else:
                        voucher_list.append(r_data)
        except:
            pass
        data['voucher_list'] = voucher_list
        data['voucher_count'] = use_count
        try:
            activitydata_set = ActivityData.objects.filter(state__in=[2, 3], customer_user=user, activity__available_begin_time__lte=datetime.datetime.now(), activity__available_end_time__gte=datetime.datetime.now()).order_by('activity__available_end_time')
            select_point = activitydata_set.filter(id__in=point_array)
            if select_point:
                select_point__sum = select_point.aggregate(Sum('remain_point'))['remain_point__sum']
                data['point_amount'] = select_point__sum / 100
            else:
                select_point__sum = 0
                data['point_amount'] = 0
            for activitydata in activitydata_set:
                r_data = ActivityDataListModelSerializer(activitydata).data
                if select_point__sum >= total_point:
                    r_data['is_choose'] = 0
                    data['point_amount'] = total_point / 100
                else:
                    r_data['is_choose'] = 1
                    data['point_amount'] = select_point__sum / 100
                if r_data['id'] in point_array:
                    r_data['choose'] = 1
                    r_data['is_choose'] = 1
                else:
                    r_data['choose'] = 0
                point_data.append(r_data)
        except:
            pass
        data['point_list'] = point_data
        return Response(data, status=status.HTTP_200_OK)

    def preferential_voucher(self, request):
        user = self.request.iser
        goods_array = self.request.data.get('goods_array', None)
        voucher_id = self.request.data.get('voucher_id', None)
        if not goods_array:
            return Response({'error': '缺少商品信息'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            max_price = Decimal('0')
            goods_set = Goods.objects.filter(id__in=goods_array)
            if not goods_set:
                return Response({'error': '无效商品id集合'}, status=status.HTTP_400_BAD_REQUEST)
            for goods in goods_set:
                if goods.price > max_price:
                    max_price = goods.price
        except:
            return Response({'error': '无效商品id'}, status=status.HTTP_400_BAD_REQUEST)
        voucher_data = []
        data = {}
        data['referential_price'] = Decimal('0')
        try:
            alidiscountcoupon_id_list = list(AliDiscountCouponGoodsAvailable.objects.filter(goods_id__in=goods_array).values_list('alidiscountcoupon_id', flat=True))
            alidiscountcouponinfo_set = AliDiscountCouponInfo.objects.filter(alidiscountcoupon__coupon_channel=3, customeruservice_id=user.id, status=1, gmt_expired__gte=datetime.datetime.now(), gmt_active__lte=datetime.datetime.now()).order_by('-total_amount')
            if alidiscountcouponinfo_set:
                total_amount__max = alidiscountcouponinfo_set.filter(alidiscountcoupon_id__in=alidiscountcoupon_id_list).aggregate(Max('total_amount'))['total_amount__max']
                if total_amount__max > max_price:
                    select_alidiscountcouponinfo = alidiscountcouponinfo_set.filter(total_amount=total_amount__max,alidiscountcoupon_id__in=alidiscountcoupon_id_list).first()
                    data['referential_price'] = select_alidiscountcouponinfo.total_amount
                else:
                    select_alidiscountcouponinfo = alidiscountcouponinfo_set.filter(alidiscountcoupon__coupon_type=6,alidiscountcoupon_id__in=alidiscountcoupon_id_list).first()
                    if select_alidiscountcouponinfo:
                        data['referential_price'] = max_price
                    else:
                        select_alidiscountcouponinfo = alidiscountcouponinfo_set.filter(total_amount=total_amount__max,alidiscountcoupon_id__in=alidiscountcoupon_id_list).first()
                        data['referential_price'] = select_alidiscountcouponinfo.total_amount
                if voucher_id:
                    select_alidiscountcouponinfo1 = alidiscountcouponinfo_set.filter(voucher_id=voucher_id).first()
                    if select_alidiscountcouponinfo1:
                        if select_alidiscountcouponinfo1.alidiscountcoupon.coupon_type == 6:
                            data['referential_price'] = max_price
                        else:
                            data['referential_price'] = select_alidiscountcouponinfo1.total_amount
                        a = 1
                    else:
                        a = 0
                else:
                    a = 0
                for alidiscountcouponinfo in alidiscountcouponinfo_set:
                    r_data = {}
                    r_data['activity_name'] = alidiscountcouponinfo.alidiscountcoupon.activity_name
                    r_data['gmt_expired'] = alidiscountcouponinfo.gmt_expired.strftime('%Y-%m-%d %H:%M:%S')
                    r_data['floor_amount'] = alidiscountcouponinfo.alidiscountcoupon.floor_amount
                    coupon_type = alidiscountcouponinfo.alidiscountcoupon.coupon_type
                    if coupon_type == 9:
                        r_data['amount'] = alidiscountcouponinfo.total_amount
                    else:
                        r_data['amount'] = max_price
                    r_data['coupon_type'] = coupon_type
                    r_data['coupon_type_str'] = alidiscountcouponinfo.alidiscountcoupon.get_coupon_type_display()
                    r_data['voucher_id'] = alidiscountcouponinfo.voucher_id
                    if alidiscountcouponinfo.alidiscountcoupon_id in alidiscountcoupon_id_list:
                        r_data['is_choose'] = 1
                    else:
                        r_data['is_choose'] = 0
                        r_data['reason'] = '限定商品可用'
                    if alidiscountcouponinfo.id == select_alidiscountcouponinfo.id:
                        voucher_data.insert(0, r_data)
                    else:
                        voucher_data.append(r_data)
                    if a == 1:
                        if alidiscountcouponinfo.voucher_id == voucher_id:
                            r_data['choose'] = 1
                        else:
                            r_data['choose'] = 0
                    else:
                        if alidiscountcouponinfo.id == select_alidiscountcouponinfo.id:
                            r_data['choose'] = 1
                        else:
                            r_data['choose'] = 0
        except:
            pass
        data['voucher_data'] = voucher_data
        return Response(data, status=status.HTTP_200_OK)

    def receive_goods(self, request):
        user = self.request.iser
        order_id = self.request.data.get('order_id', None)
        if not order_id:
            return Response({'error': '缺少必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            order = self.get_queryset().get(id=order_id)
        except:
            return Response({'error': '无效订单id'}, status=status.HTTP_400_BAD_REQUEST)
        if order.state != 6:
            return Response({'error': '订单状态有误'}, status=status.HTTP_400_BAD_REQUEST)
        order.state = 14
        order.save()
        # OrderAdvance.objects.create(
        #     order_id=order.id,
        #     status=4,
        #     remark='用户确认收货',
        #     customeruservice_id=user.id
        # )
        try:
            # if order.is_profit_sharing in [1, 3]:
            #     if order.is_profit_sharing == 1:
            #         out_trade_no = f'{datetime.datetime.now().strftime("%Y%m%d%H%M%S")}{"%06d" % randint(0, 999999)}'
            #         body = {
            #             "program_id": "202316837141378884",
            #             "shop_id": order.merchant.ruiyinxinMerchantID,
            #             "order_id": out_trade_no,
            #             "out_trade_no": order.orderNum,
            #             "is_profit": "0"
            #         }
            #         result = ryx_profitsharing_order(body)
            #     else:
            #         out_trade_no = f'{datetime.datetime.now().strftime("%Y%m%d%H%M%S")}{"%06d" % randint(0, 999999)}'
            #         body = {
            #             "program_id": "202316837141378884",
            #             "shop_id": order.merchant.ruiyinxinMerchantID,
            #             "order_id": out_trade_no,
            #             "out_trade_no": order.orderNum,
            #             "is_profit": "2"
            #         }
            #         result = ryx_profitsharing_order(body)
            #     profitorder = OrderProfitSharing.objects.filter(order_id=order.id).first()
            #     if not profitorder:
            #         profitorder, create = OrderProfitSharing.objects.get_or_create(defaults={'order_id': order.id, "out_trade_no": out_trade_no}, order_id=order.id)
            #     if result['result_code'] == 'success':
            #         order.is_profit_sharing = 2
            #         profitorder.profit_order_id = result['profit_order_id']
            #         profitorder.profit_time = datetime.datetime.now()
            #         profitorder.save()
            #         receipts_time = datetime.datetime.now().strftime('%Y-%m-%d')
            #         bill = MerchantBill.objects.filter(receipts_time=receipts_time, merchant_id=order.merchant_id, bill_type=order.order_species).first()
            #         if not bill:
            #             bill_data = {}
            #             bill_data['merchant_id'] = order.merchant_id
            #             bill_data['receipts_time'] = receipts_time
            #             bill_data['amount'] = order.total_price
            #             bill_data['commission'] = order.freight
            #             bill_data['level_id'] = order.merchant.level_id
            #             bill_data['payable_amount'] = order.total_price - order.freight
            #             bill_data['channel_id'] = 3
            #             bill_data['bill_type'] = order.order_species
            #             bill, create = MerchantBill.objects.get_or_create(defaults=bill_data, receipts_time=receipts_time, merchant_id=order.merchant_id, bill_type=order.order_species)
            #         else:
            #             bill.amount = bill.amount + order.total_price
            #             bill.commission = bill.commission + order.freight
            #             bill.payable_amount = bill.payable_amount + order.total_price - order.freight
            #             bill.save()
            #         order.payable_settled_amount = order.total_price - order.freight
            #         order.bill_id = bill.id
            #         order.save()
            #     else:
            #         profitorder.error_msg = result['error_msg']
            #         profitorder.profit_status = 2
            #         profitorder.save()
            #         OrderAdvance.objects.create(
            #             order_id=order.id,
            #             status=4,
            #             remark='用户确认收货,解冻资金出错',
            #             customeruservice_id=user.id
            #         )
            if order.is_profit_sharing == 1:
                out_trade_no = f'{datetime.datetime.now().strftime("%Y%m%d%H%M%S")}{"%06d" % randint(0, 999999)}'
                body = {
                    "program_id": "202316837141378884",
                    "shop_id": order.merchant.ruiyinxinMerchantID,
                    "order_id": out_trade_no,
                    "out_trade_no": order.orderNum,
                    "is_profit": "0"
                }
                result = ryx_profitsharing_order(body)
                profitorder = OrderProfitSharing.objects.filter(order_id=order.id).first()
                if not profitorder:
                    profitorder, create = OrderProfitSharing.objects.get_or_create(defaults={'order_id': order.id, "out_trade_no": out_trade_no}, order_id=order.id)
                if result['result_code'] == 'success':
                    order.is_profit_sharing = 2
                    order.save()
                    profitorder.profit_order_id = result['profit_order_id']
                    profitorder.profit_time = datetime.datetime.now()
                    profitorder.save()
                    OrderAdvance.objects.create(
                        order_id=order.id,
                        status=5,
                        remark='用户确认收货,解冻资金',
                        customeruservice_id=user.id
                    )
                    receipts_time = datetime.datetime.now().strftime('%Y-%m-%d')
                    bill = MerchantBill.objects.filter(receipts_time=receipts_time, merchant_id=order.merchant_id, bill_type=order.order_species).first()
                    if not bill:
                        bill_data = {}
                        bill_data['merchant_id'] = order.merchant_id
                        bill_data['receipts_time'] = receipts_time
                        bill_data['amount'] = order.total_price
                        bill_data['commission'] = order.freight
                        bill_data['level_id'] = order.merchant.level_id
                        bill_data['payable_amount'] = order.total_price - order.freight
                        bill_data['channel_id'] = 3
                        bill_data['bill_type'] = order.order_species
                        bill, create = MerchantBill.objects.get_or_create(defaults=bill_data,
                                                                          receipts_time=receipts_time,
                                                                          merchant_id=order.merchant_id,
                                                                          bill_type=order.order_species)
                    else:
                        bill.amount = bill.amount + order.total_price
                        bill.commission = bill.commission + order.freight
                        bill.payable_amount = bill.payable_amount + order.total_price - order.freight
                        bill.save()
                    order.payable_settled_amount = order.total_price - order.freight
                    order.bill_id = bill.id
                    order.save()
                else:
                    order.is_profit_sharing = 2
                    order.save()
                    profitorder.error_msg = result['error_msg']
                    profitorder.profit_status = 2
                    profitorder.save()
                    OrderAdvance.objects.create(
                        order_id=order.id,
                        status=4,
                        remark='用户确认收货,解冻资金出错',
                        customeruservice_id=user.id
                    )
            elif order.is_profit_sharing == 3:
                out_trade_no = f'{datetime.datetime.now().strftime("%Y%m%d%H%M%S")}{"%06d" % randint(0, 999999)}'
                body = {
                    "program_id": "202316837141378884",
                    "shop_id": order.merchant.ruiyinxinMerchantID,
                    "order_id": out_trade_no,
                    "out_trade_no": order.orderNum,
                    "is_profit": "2"
                }
                result = ryx_profitsharing_order(body)
                profitorder = OrderProfitSharing.objects.filter(order_id=order.id).first()
                if not profitorder:
                    profitorder, create = OrderProfitSharing.objects.get_or_create(
                        defaults={'order_id': order.id, "out_trade_no": out_trade_no}, order_id=order.id)
                if result['result_code'] == 'success':
                    order.is_profit_sharing = 4
                    order.save()
                    profitorder.profit_order_id = result['profit_order_id']
                    profitorder.profit_time = datetime.datetime.now()
                    profitorder.save()
                    OrderAdvance.objects.create(
                        order_id=order.id,
                        status=5,
                        remark='用户确认收货,解冻资金',
                        customeruservice_id=user.id
                    )
                    receipts_time = datetime.datetime.now().strftime('%Y-%m-%d')
                    bill = MerchantBill.objects.filter(receipts_time=receipts_time, merchant_id=order.merchant_id,
                                                       bill_type=order.order_species).first()
                    if not bill:
                        bill_data = {}
                        bill_data['merchant_id'] = order.merchant_id
                        bill_data['receipts_time'] = receipts_time
                        bill_data['amount'] = order.total_price
                        bill_data['commission'] = order.freight
                        bill_data['level_id'] = order.merchant.level_id
                        bill_data['payable_amount'] = order.total_price - order.freight
                        bill_data['channel_id'] = 3
                        bill_data['bill_type'] = order.order_species
                        bill, create = MerchantBill.objects.get_or_create(defaults=bill_data,
                                                                          receipts_time=receipts_time,
                                                                          merchant_id=order.merchant_id,
                                                                          bill_type=order.order_species)
                    else:
                        bill.amount = bill.amount + order.total_price
                        bill.commission = bill.commission + order.freight
                        bill.payable_amount = bill.payable_amount + order.total_price - order.freight
                        bill.save()
                    order.payable_settled_amount = order.total_price - order.freight
                    order.bill_id = bill.id
                    order.save()
                else:
                    order.is_profit_sharing = 4
                    order.save()
                    profitorder.error_msg = result['error_msg']
                    profitorder.profit_status = 2
                    profitorder.save()
                    OrderAdvance.objects.create(
                        order_id=order.id,
                        status=4,
                        remark='用户确认收货,解冻资金出错',
                        customeruservice_id=user.id
                    )
        except:
            pass
        return Response({'success': '操作成功'}, status=status.HTTP_200_OK)

    def update(self, request, *args, **kwargs):
        user = self.request.iser
        instance = self.get_object()
        if instance.order_type != 5:
            return Response({'error': '订单类型有误'}, status=status.HTTP_400_BAD_REQUEST)
        reason_id = self.request.data.get('reason_id', None)
        description = self.request.data.get('description', None)
        img_array = self.request.data.get('img_array', None)
        if not reason_id:
            return Response({'error': '请上传退款原因'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            reason = AfterSaleReason.objects.get(id=reason_id, is_delete=0)
        except:
            return Response({'error': '无效原因'}, status=status.HTTP_400_BAD_REQUEST)
        # if reason.reason_type == 1 and instance.state != 9:
        #     return Response({'error': '订单已发货,请收到货品后申请退货处理'}, status=status.HTTP_400_BAD_REQUEST)
        if reason.reason_type == 2:
            if instance.state != 14:
                return Response({'error': '请在收到货品之后再申请退货处理'}, status=status.HTTP_400_BAD_REQUEST)
            if instance.payment_time <= (datetime.datetime.now()+datetime.timedelta(days=-30)):
                return Response({'error': '超过30天订单无法操作退款处理'}, status=status.HTTP_400_BAD_REQUEST)
        if reason.reason_type == 3:
            if instance.state != 14:
                return Response({'error': '请在收到货品之后再申请退货处理'}, status=status.HTTP_400_BAD_REQUEST)
        if img_array and type(img_array) != list:
            return Response({'error': '凭证资料数据类型有误'}, status=status.HTTP_400_BAD_REQUEST)
        with transaction.atomic():
            # 创建事务保存点
            save_id = transaction.savepoint()
            try:
                application_num = f'{datetime.datetime.now().strftime("%Y%m%d%H%M%S")}{"%06d" % randint(0, 999999)}'
                form_data = {}
                form_data['order_id'] = instance.id
                form_data['order_status'] = instance.state
                form_data['description'] = description
                form_data['reason_id'] = reason.id
                form_data['application_num'] = application_num
                form_data['customeruservice_id'] = user.id
                form_data['refund_money'] = instance.realpay_amount
                form_data['reason_type'] = reason.reason_type
                form_data['form_status'] = 8
                form = AfterSaleApplicationForm.objects.create(**form_data)
                if img_array:
                    for img in img_array:
                        AfterSaleApplicationFormImg.objects.create(applicationform_id=form.id, img=img.replace("https://circle.sutpay.cn/", ""))
                instance.state = 5
                instance.save()
                transaction.savepoint_commit(save_id)
                return Response({'success': '发起申请成功', "id": form.id}, status=status.HTTP_200_OK)
            except:
                transaction.savepoint_rollback(save_id)
                return Response({'error': '发起申请失败'}, status=status.HTTP_400_BAD_REQUEST)

    def update_address(self, request):
        user = self.request.iser
        order_id = self.request.data.get('order_id', None)
        address_id = self.request.data.get('address_id', None)
        if not order_id:
            return Response({'error': '请上传订单id'}, status=status.HTTP_400_BAD_REQUEST)
        if not address_id:
            return Response({'error': '请上传地址信息'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            order = self.get_queryset().get(id=order_id)
        except:
            return Response({'error': '无效订单id'}, status=status.HTTP_400_BAD_REQUEST)
        if order.order_type != 5:
            return Response({'error': '此订单不支持修改配送地址'}, status=status.HTTP_400_BAD_REQUEST)
        if order.state != 9:
            return Response({'error': '订单状态有误'}, status=status.HTTP_400_BAD_REQUEST)
        address = CustomerUserViceAddress.objects.filter(customeruservice_id=user.id, id=address_id, is_deleted=0).first()
        if not address:
            return Response({'error': '无效配送信息'}, status=status.HTTP_400_BAD_REQUEST)
        orderaddress = order.orderaddress
        orderaddress.receiver = address.receiver
        orderaddress.province = address.province
        orderaddress.city = address.city
        orderaddress.district = address.district
        orderaddress.place = address.place
        orderaddress.mobile = address.mobile
        orderaddress.longitude = address.longitude
        orderaddress.latitude = address.latitude
        orderaddress.save()
        return Response({'error': '修改成功'}, status=status.HTTP_200_OK)

    def group_data(self, request):
        user = self.request.iser
        account = self.request.query_params.get('account', None)
        group = OrderInfoGROUP.objects.filter(account=account).first()
        if not group:
            return Response({'error': '无效拼团订单'}, status=status.HTTP_400_BAD_REQUEST)
        main_order = OrderInfo.objects.get(id=group.order_id)
        if main_order.customeruservice_id == user.id:
            is_self = 1
        else:
            is_self = 0
        if group.group_status == 1:
            cancel_group_order(group)
            group = OrderInfoGROUP.objects.filter(account=account).first()
        data = {}
        data['group_status'] = ''
        data['expired_time'] = ''
        data['account'] = ''
        data['people_list'] = []
        data['count'] = ''
        data['is_self'] = is_self
        try:
            if group:
                data['group_status'] = group.group_status
                data['expired_time'] = group.expired_time.strftime("%Y-%m-%d %H:%M:%S")
                data['account'] = group.account
                order_set = OrderInfo.objects.filter(group_id=group.id, state__in=[15, 2, 8, 1])
                count = group.group_order_num - len(order_set)
                data['count'] = count
                for order in order_set:
                    customeruservice = order.customeruservice
                    if customeruservice.avatar:
                        data['people_list'].append(customeruservice.avatar)
                    else:
                        data['people_list'].append('https://suppliera.postwork.cn/static/img/header.f38b3311.png')
                for i in range(count):
                    data['people_list'].append('https://jinjian.sutpay.cn/image/wyh_img128.png')
        except:
            pass
        return Response(data, status=status.HTTP_200_OK)

    def group_share_pic(self, request):
        user = self.request.iser
        account = self.request.data.get('keyword', None)
        img = self.request.FILES.get('img', None)
        if not all([img]):
            return Response({'error': '缺少必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        if img.size > 2097152:
            return Response({'error': '照片不得超过2M,请重新上传!'}, status=status.HTTP_400_BAD_REQUEST)
        img_str = img.read()
        img.seek(0)
        group = OrderInfoGROUP.objects.filter(account=account).first()
        if not group:
            return Response({'error': '无效拼团订单'}, status=status.HTTP_400_BAD_REQUEST)
        # if group.share_pic:
        #     return Response({'success': '操作成功', 'img_id': group.share_pic.url}, status=status.HTTP_200_OK)
        try:
            mid_img = pic_upload(img_str)
            group.share_pic = mid_img
            group.save()
        except Exception as e:
            logger.error(e)
            return Response({'error': '头像上传失败,请重新上传!'}, status=status.HTTP_400_BAD_REQUEST)
        return Response({'success': '操作成功', 'img_id': f'https://circle.sutpay.cn/{mid_img}'}, status=status.HTTP_200_OK)

    def sd_use_store(self, request):
        longitude = self.request.query_params.get('longitude', '')
        latitude = self.request.query_params.get('latitude', '')
        city_code = self.request.query_params.get('city_code', '')
        district_code = self.request.query_params.get('district_code', '')
        order_id = self.request.query_params.get('order_id', None)
        distance = self.request.query_params.get('distance', 2000)
        search = self.request.query_params.get('search', '')
        if not order_id:
            return Response({'error': '缺少订单id'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            distance = int(distance)
            distance = distance * 1.5
            if distance > 50000:
                return Response({'error': '搜索距离不能大于50公里'}, status=status.HTTP_400_BAD_REQUEST)
            distance = distance/1000
        except:
            return Response({'error': '距离参数格式有误'}, status=status.HTTP_400_BAD_REQUEST)
        if not all([latitude, longitude]):
            return Response({'error': '请上传定位经纬度'}, status=status.HTTP_400_BAD_REQUEST)
        conn = pymysql.connect(host=settings.DATABASES['default']['HOST'],
                               port=settings.DATABASES['default']['PORT'],
                               database=settings.DATABASES['default']['NAME'],
                               user=settings.DATABASES['default']['USER'],
                               password=settings.DATABASES['default']['PASSWORD'])
        cursor = conn.cursor(cursor=pymysql.cursors.SSDictCursor)
        condition = 'WHERE store_status IN (1,2)'
        if district_code or city_code or search:
            if district_code:
                condition += f' AND areaCode={district_code}'
            if city_code:
                condition += f' AND cityCode={city_code}'
            if search:
                condition += f' AND store_name LIKE "%{search}%"'
            condition += ' ORDER BY distance'
        else:
            condition += f' HAVING distance<{distance} ORDER BY distance'
        sql = f'''SELECT id,store_name,gd_longitude AS longitude,gd_latitude AS latitude,address,contactPerson,telephone,openTime,closingTime,grade,facadeImageUrl,logoImageUrl,loungeImageUrl,workspaceImageUrl,services,(6371 * acos(cos(radians({latitude})) * cos(radians(gd_latitude)) * cos( radians(gd_longitude) - radians({longitude})) + sin(radians({latitude})) * sin(radians(gd_latitude)))) AS distance FROM tb_order_schengle_coupons_store {condition};'''
        try:
            cursor.execute(sql)
            rows = cursor.fetchall()
        finally:
            cursor.close()
            conn.close()
        data = {}
        if search or district_code or city_code:
            if rows:
                latitude = rows[0]['latitude']
                longitude = rows[0]['longitude']
        for row in rows:
            slideshow = []
            distance = row['distance']
            if distance < 1:
                row['distance'] = f'{int(distance * 1000)} m'
            else:
                row['distance'] = f'{Decimal(str(distance)).quantize(Decimal("0.00"))} km'
            row['services'] = json.loads(row['services'])
            if row['facadeImageUrl']:
                slideshow.append(row['facadeImageUrl'])
            if row['loungeImageUrl']:
                slideshow.append(row['loungeImageUrl'])
            if row['workspaceImageUrl']:
                slideshow.append(row['workspaceImageUrl'])
            row['slideshow'] = slideshow
        data['lists'] = rows
        data['latitude'] = latitude
        data['longitude'] = longitude
        return Response(data, status=status.HTTP_200_OK)


class OrderGoodsModelViewSet(ModelViewSet):

    pagination_class = MyPage
    filter_backends = (filters.SearchFilter, DjangoFilterBackend)
    search_fields = ('merchant__name', 'goods__name')
    filter_class = OrderGoodsFilter

    def get_queryset(self):
        user = self.request.iser
        queryset = OrderGoods.objects.filter(order__customeruservice_id=user.id, order__state__in=[14, 3]).order_by('-id', '-comment_time')
        try:
            if '_mutable' in self.request.data.__dict__:
                self.request.data.__dict__['_mutable'] = True
        except:
            pass
        self.request.data['commented_count'] = str(queryset.filter(is_commented=1).count())
        self.request.data['not_commented_count'] = str(queryset.filter(is_commented=0).count())
        return queryset

    def get_serializer_class(self):
        if self.action == 'list':
            return OrderGoodsListModelSerializer
        else:
            return OrderGoodsRetrieveModelSerializer

    def comment_file(self, request):
        user = self.request.iser
        file = self.request.FILES.get('file', None)
        if not all([file]):
            return Response({'error': '缺少必传参数!'}, status=status.HTTP_400_BAD_REQUEST)
        # if file.size > 2097152:
        #     return Response({'error': '照片不得超过2M,请重新上传!'}, status=status.HTTP_400_BAD_REQUEST)
        img_str = file.read()
        file.seek(0)
        try:
            img_id = f'youhuiquanyi/comment/{random_str()}'
            mid_img = pic_upload(img_str, key=img_id)
        except Exception as e:
            logger.error(e)
            return Response({'error': '文件上传失败,请重新上传!'}, status=status.HTTP_400_BAD_REQUEST)
        return Response({'success': '上传成功', 'file_id': img_id, 'file_url': f'https://circle.sutpay.cn/{img_id}'}, status=status.HTTP_200_OK)

    def comment(self, request):
        user = self.request.iser
        is_anonymous = self.request.data.get('is_anonymous', 0)
        comment = self.request.data.get('comment', None)
        score = self.request.data.get('score', 10)
        file_array = self.request.data.get('file_array', None)
        ordergoods_id = self.request.data.get('ordergoods_id', None)
        if not all([ordergoods_id, comment]):
            return Response({'error': '缺少必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            ordergoods = OrderGoods.objects.get(id=ordergoods_id)
        except:
            return Response({'error': '无效订单商品id'}, status=status.HTTP_400_BAD_REQUEST)
        if ordergoods.is_commented == 1:
            return Response({'error': '不可重复评价'}, status=status.HTTP_400_BAD_REQUEST)
        order = ordergoods.order
        if order.customeruservice_id != user.id:
            return Response({'error': '您无权评价该订单'}, status=status.HTTP_400_BAD_REQUEST)
        if order.state not in [3, 14]:
            return Response({'error': '订单未完成不可评价'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            for file_data in file_array:
                file_data['ordergoods_id'] = ordergoods_id
                OrderGoodsCommentFile.objects.create(**file_data)
        except:
            return Response({'error': '文件格式有误'}, status=status.HTTP_400_BAD_REQUEST)
        ordergoods.comment = comment
        ordergoods.score = 1
        ordergoods.is_anonymous = is_anonymous
        ordergoods.is_commented = 1
        ordergoods.comment_time = datetime.datetime.now()
        ordergoods.save()
        return Response({'success': '评价成功', 'id': ordergoods.id}, status=status.HTTP_200_OK)

    def update(self, request, *args, **kwargs):
        instance = self.get_object()
        if instance.is_anonymous == 0:
            instance.is_anonymous = 1
        else:
            instance.is_anonymous = 0
        instance.save()
        return Response({'success': '操作成功'}, status=status.HTTP_200_OK)


class GoodsCommentModelViewSet(ModelViewSet):

    pagination_class = MyPage
    filter_backends = (filters.SearchFilter, DjangoFilterBackend)
    search_fields = ('merchant__name', 'goods__name')
    filter_class = OrderGoodsFilter
    serializer_class = GoodsCommentModelSerializer

    def get_queryset(self):
        queryset = OrderGoods.objects.filter(is_commented=1).order_by('-id')
        return queryset


class GoodsModelViewSet(ModelViewSet):
    '''商品'''

    pagination_class = MyPage
    filter_backends = (filters.SearchFilter, DjangoFilterBackend)
    filter_class = GoodsFilter
    search_fields = ('name',)

    def get_queryset(self):
        user = self.request.iser
        sale_sort = self.request.query_params.get('sale_sort', '')
        price_sort = self.request.query_params.get('price_sort', '')
        soldout = self.request.query_params.get('soldout', '')
        level_id = self.request.query_params.get('level_id', '')
        account = self.request.query_params.get('account', '')
        merchant_id = self.request.query_params.get('merchant_id', '')
        coupon_id = self.request.query_params.get('coupon_id', '')
        is_filter = self.request.query_params.get('is_filter', '')
        is_newyear = self.request.query_params.get('is_newyear', '')
        activity_id = self.request.query_params.get('activity_id', '')
        longitude = self.request.query_params.get('longitude', '')
        latitude = self.request.query_params.get('latitude', '')
        city_id = self.request.query_params.get('city_id', '')
        district_id = self.request.query_params.get('district_id', '')
        stock_id = self.request.query_params.get('stock_id', '')
        goods_tag = self.request.query_params.get('goods_tag', '')
        try:
            merchant = Merchant.objects.get(id=merchant_id)
            if merchant.is_mall != 2:
                return Goods.objects.filter(id=1)
        except:
            pass
        if self.action == 'list':
            if soldout == '1':
                if level_id:
                    queryset = Goods.objects.filter(is_launched=1, launchedgoods__stock__gt=0, launchedgoods__is_launched=1, launchedgoods__level_id=level_id).distinct().order_by('-launchedgoods__stock')
                else:
                    queryset = Goods.objects.filter(is_launched=1, stock__gt=0).order_by('-stock')
            elif soldout == '2':
                if level_id:
                    queryset = Goods.objects.filter(is_launched=1, launchedgoods__stock=0, launchedgoods__is_launched=1, launchedgoods__level_id=level_id).distinct().order_by('-launchedgoods__stock')
                else:
                    queryset = Goods.objects.filter(is_launched=1, stock=0).order_by('-stock')
            else:
                if level_id:
                    queryset = Goods.objects.filter(is_launched=1, launchedgoods__is_launched=1, launchedgoods__level_id=level_id).distinct().order_by('-launchedgoods__stock')
                else:
                    queryset = Goods.objects.filter(is_launched=1).order_by('-stock')
            if str(is_newyear) == '1':
                queryset = queryset.filter(goods_tag='gdnhj')
        else:
            if level_id:
                queryset = Goods.objects.filter(is_launched=1).order_by('-launchedgoods__stock')
            else:
                queryset = Goods.objects.filter(is_launched=1).order_by('-stock')
        self.request.data['banner_short'] = 'https://jinjian.sutpay.cn/image/wyh_bg102_1.png'
        self.request.data['banner_long'] = 'https://jinjian.sutpay.cn/image/wyh_bg87_1.png'
        self.request.data['title_level'] = {"name": '', "level_id": ''}
        if level_id:
            level = Level.objects.filter(id=level_id).first()
            if level:
                self.request.data['title_level'] = {"name": level.name, "level_id": level.id}
        if account:
            level = Level.objects.filter(account=account).first()
            if level:
                self.request.data['title_level'] = {"name": level.name, "level_id": level.id}
        if coupon_id:
            alidiscountcouponinfo = AliDiscountCouponInfo.objects.filter(voucher_id=coupon_id).first()
            if alidiscountcouponinfo:
                alidiscountcoupon = alidiscountcouponinfo.alidiscountcoupon
                goods_id_list = AliDiscountCouponGoodsAvailable.objects.filter(alidiscountcoupon_id=alidiscountcouponinfo.alidiscountcoupon_id).values_list('goods_id', flat=True)
                queryset = queryset.filter(id__in=list(goods_id_list))
                try:
                    if '_mutable' in self.request.data.__dict__:
                        self.request.data.__dict__['_mutable'] = True
                except:
                    pass
                alidiscountcouponinfo_data = {}
                if alidiscountcouponinfo.customeruservice_id == user.id:
                    alidiscountcouponinfo_data['activity_name'] = alidiscountcoupon.activity_name
                    alidiscountcouponinfo_data['publish_time'] = f'{alidiscountcoupon.publish_start_time.strftime("%Y-%m-%d")}-{alidiscountcoupon.publish_end_time.strftime("%Y-%m-%d")}'
                    alidiscountcouponinfo_data['description'] = '仅限本页面下单使用'
                    alidiscountcouponinfo_data['floor_amount'] = alidiscountcoupon.floor_amount
                    if alidiscountcoupon.coupon_type == 6:
                        alidiscountcouponinfo_data['amount'] = '单品券'
                    else:
                        alidiscountcouponinfo_data['amount'] = alidiscountcoupon.amount
                    alidiscountcouponinfo_data['coupon_type'] = alidiscountcoupon.coupon_type
                    alidiscountcouponinfo_data['coupon_type_str'] = alidiscountcoupon.get_coupon_type_display()
                    alidiscountcouponinfo_data['coupon_status'] = alidiscountcoupon.coupon_status
                    alidiscountcouponinfo_data['coupon_status_str'] = alidiscountcoupon.get_coupon_status_display()
                    if alidiscountcoupon.banner_short:
                        self.request.data['banner_short'] = alidiscountcoupon.banner_short.url
                    if alidiscountcoupon.banner_long:
                        self.request.data['banner_long'] = alidiscountcoupon.banner_long.url
                    self.request.data['alidiscountcouponinfo'] = alidiscountcouponinfo_data
                else:
                    self.request.data['alidiscountcouponinfo'] = '无权限访问'
            else:
                self.request.data['alidiscountcouponinfo'] = '无权限访问'
        if activity_id:
            alidiscountcoupon = AliDiscountCoupon.objects.filter(id=activity_id).first()
            if alidiscountcoupon:
                goods_id_list = AliDiscountCouponGoodsAvailable.objects.filter(alidiscountcoupon_id=alidiscountcoupon.id).values_list('goods_id', flat=True)
                queryset = queryset.filter(id__in=list(goods_id_list))
                if alidiscountcoupon.banner_short:
                    self.request.data['banner_short'] = alidiscountcoupon.banner_short.url
                if alidiscountcoupon.banner_long:
                    self.request.data['banner_long'] = alidiscountcoupon.banner_long.url
        if stock_id:
            alidiscountcoupon = AliDiscountCoupon.objects.filter(template_id=stock_id).first()
            if alidiscountcoupon:
                queryset = queryset.filter(goods_tag=alidiscountcoupon.goods_tag)
                if alidiscountcoupon.banner_short:
                    self.request.data['banner_short'] = alidiscountcoupon.banner_short.url
                if alidiscountcoupon.banner_long:
                    self.request.data['banner_long'] = alidiscountcoupon.banner_long.url
        if goods_tag:
            queryset = queryset.filter(goods_tag=goods_tag)
        if city_id:
            queryset = queryset.filter(area__city_id=city_id)
        if district_id:
            queryset = queryset.filter(area__district_id=district_id)
        if all([longitude, latitude]):
            gcd_formula = "6371 * acos(least(greatest(cos(radians(%s)) * cos(radians(latitude)) * cos(radians(longitude) - radians(%s)) + sin(radians(%s)) * sin(radians(latitude)) , -1), 1))"
            sql = RawSQL(gcd_formula, (latitude, longitude, latitude))
            queryset = queryset.annotate(distance=sql).order_by(F('distance').asc(nulls_last=True))
        if sale_sort == '1':
            queryset = queryset.order_by('sales')
        elif sale_sort == '2':
            queryset = queryset.order_by('-sales')
        elif price_sort == '1':
            queryset = queryset.order_by('price')
        elif price_sort == '2':
            queryset = queryset.order_by('-price')
        else:
            queryset = queryset.order_by('-sort', 'id')
        if str(is_filter) == '81':
            queryset = Goods.objects.filter(id=30206962)
        return queryset

    def get_serializer_class(self):
        if self.action == 'list':
            return GoodsListModelSerializer
        else:
            return GoodsRetrieveModelSerializer

    def get_serializer_context(self):
        level_id = self.request.query_params.get('level_id', None)
        return {'level_id': level_id}

    def goods_area(self, request):
        longitude = self.request.query_params.get('longitude', '')
        latitude = self.request.query_params.get('latitude', '')
        try:
            if all([longitude, latitude]):
                url = f'https://apis.map.qq.com/ws/geocoder/v1/?location={latitude},{longitude}&key=TV7BZ-AZDW4-4Y5UQ-FWV4T-R7NVE-UWFZV'
                response = requests.get(url=url)
                result = response.json()
                if 'result' in result:
                    adcode = result['result']['ad_info']['adcode']
                    hit = GoodsAreaCode.objects.filter(district_code=adcode).first()
                else:
                    hit = None
            else:
                hit = None
        except:
            hit = None
        curCity = 0
        curCity_hit = 0
        curCity_hit1 = 0
        curDis = 0
        curDis_hit = 0
        data = []
        city_set = GoodsAreaCode.objects.filter(prov_id=1935, level=2)
        if not hit:
            data1 = {}
            data1['id'] = ''
            data1['name'] = '不限'
            data1['is_hit'] = 1
            data1['code'] = ''
            data1['child_data'] = [{"id": "", "name": "不限", 'is_hit': 1, 'code': ''}]
            data.append(data1)
            for city in city_set:
                data1 = {}
                data1['id'] = city.id
                data1['name'] = city.name
                data1['is_hit'] = 0
                data1['code'] = city.city_code
                district_set = GoodsAreaCode.objects.filter(prov_id=1935, level=3, city_id=city.id)
                child_data = []
                data2 = {}
                data2['id'] = ''
                data2['name'] = '不限'
                data2['is_hit'] = 0
                data2['code'] = ''
                child_data.append(data2)
                for district in district_set:
                    data2 = {}
                    data2['id'] = district.id
                    data2['name'] = district.name
                    data2['is_hit'] = 0
                    data2['code'] = district.district_code
                    child_data.append(data2)
                data1['child_data'] = child_data
                data.append(data1)
        else:
            hit_city_id = hit.city_id
            hit_district_id = hit.district_id
            data1 = {}
            data1['id'] = ''
            data1['name'] = '不限'
            data1['is_hit'] = 0
            data1['code'] = ''
            data1['child_data'] = [{"id": "", "name": "不限", 'is_hit': 0, 'code': ''}]
            data.append(data1)
            for city in city_set:
                if not curCity_hit:
                    curCity += 1
                data1 = {}
                data1['id'] = city.id
                data1['name'] = city.name
                data1['code'] = city.city_code
                if hit_city_id == city.id:
                    data1['is_hit'] = 1
                    curCity_hit = 1
                else:
                    data1['is_hit'] = 0
                district_set = GoodsAreaCode.objects.filter(prov_id=1935, level=3, city_id=city.id)
                child_data = []
                data2 = {}
                data2['id'] = ''
                data2['name'] = '不限'
                data2['is_hit'] = 0
                data2['code'] = ''
                child_data.append(data2)
                if curCity_hit1 == 0:
                    curDis = 0
                    curDis_hit = 0
                for district in district_set:
                    if not curDis_hit:
                        curDis += 1
                    data2 = {}
                    data2['id'] = district.id
                    data2['name'] = district.name
                    data2['code'] = district.district_code
                    if hit_district_id == district.id:
                        data2['is_hit'] = 0
                        curDis_hit = 1
                        curCity_hit1 = 1
                    else:
                        data2['is_hit'] = 0
                    child_data.append(data2)
                data1['child_data'] = child_data
                data.append(data1)
        return Response({"data": data, "curCity": curCity, "curDis": 0}, status=status.HTTP_200_OK)

    def goods_area1(self, request):
        longitude = self.request.query_params.get('longitude', '')
        latitude = self.request.query_params.get('latitude', '')
        try:
            if all([longitude, latitude]):
                url = f'https://apis.map.qq.com/ws/geocoder/v1/?location={latitude},{longitude}&key=TV7BZ-AZDW4-4Y5UQ-FWV4T-R7NVE-UWFZV'
                response = requests.get(url=url)
                result = response.json()
                if 'result' in result:
                    adcode = result['result']['ad_info']['adcode']
                    hit = GoodsAreaCode.objects.filter(district_code=adcode).first()
                else:
                    hit = None
            else:
                hit = None
        except:
            hit = None
        curCity = 0
        curCity_hit = 0
        curCity_hit1 = 0
        curDis = 0
        curDis_hit = 0
        data = []
        city_set = GoodsAreaCode.objects.filter(prov_id=1935, level=2)
        if not hit:
            data1 = {}
            data1['id'] = ''
            data1['name'] = '不限'
            data1['is_hit'] = 1
            data1['child_data'] = [{"id": "", "name": "不限", 'is_hit': 1}]
            data.append(data1)
            for city in city_set:
                data1 = {}
                data1['id'] = city.id
                data1['name'] = city.name
                data1['is_hit'] = 0
                district_set = GoodsAreaCode.objects.filter(prov_id=1935, level=3, city_id=city.id)
                child_data = []
                data2 = {}
                data2['id'] = ''
                data2['name'] = '不限'
                data2['is_hit'] = 0
                child_data.append(data2)
                for district in district_set:
                    data2 = {}
                    data2['id'] = district.id
                    data2['name'] = district.name
                    data2['is_hit'] = 0
                    child_data.append(data2)
                data1['child_data'] = child_data
                data.append(data1)
        else:
            hit_city_id = hit.city_id
            hit_district_id = hit.district_id
            data1 = {}
            data1['id'] = ''
            data1['name'] = '不限'
            data1['is_hit'] = 0
            data1['child_data'] = [{"id": "", "name": "不限", 'is_hit': 0}]
            data.append(data1)
            for city in city_set:
                if not curCity_hit:
                    curCity += 1
                data1 = {}
                data1['id'] = city.id
                data1['name'] = city.name
                if hit_city_id == city.id:
                    data1['is_hit'] = 1
                    curCity_hit = 1
                else:
                    data1['is_hit'] = 0
                district_set = GoodsAreaCode.objects.filter(prov_id=1935, level=3, city_id=city.id)
                child_data = []
                data2 = {}
                data2['id'] = ''
                data2['name'] = '不限'
                data2['is_hit'] = 0
                child_data.append(data2)
                if curCity_hit1 == 0:
                    curDis = 0
                    curDis_hit = 0
                for district in district_set:
                    if not curDis_hit:
                        curDis += 1
                    data2 = {}
                    data2['id'] = district.id
                    data2['name'] = district.name
                    if hit_district_id == district.id:
                        data2['is_hit'] = 0
                        curDis_hit = 1
                        curCity_hit1 = 1
                    else:
                        data2['is_hit'] = 0
                    child_data.append(data2)
                data1['child_data'] = child_data
                data.append(data1)
        return Response({"data": data, "curCity": curCity, "curDis": 0}, status=status.HTTP_200_OK)


class CashActivityDataModelViewSet(ModelViewSet):

    pagination_class = MyPage
    filter_backends = (filters.SearchFilter, DjangoFilterBackend)

    def get_serializer_class(self):
        if self.action == 'list':
            return CashActivityDataListModelSerializer
        else:
            return CashActivityDataRetrieveModelSerializer

    def get_queryset(self):
        user = self.request.iser
        queryset = CashActivityData.objects.filter(customeruservice_id=user.id).order_by('-create_time')
        try:
            if '_mutable' in self.request.data.__dict__:
                self.request.data.__dict__['_mutable'] = True
        except:
            pass
        # self.request.data['use_count'] = str(queryset.filter(state__in=[2,3]).count())
        # self.request.data['not_use_count'] = str(queryset.exclude(state__in=[2,3]).count())
        return queryset

    def bank_allow_cash(self, request):
        user = self.request.iser
        identify = self.request.query_params.get('identify', None)
        if not identify:
            return Response({'error': '缺少必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            activity_data = CashActivityData.objects.get(identify=identify)
        except:
            return Response({'error': '无效二维码,请联系管理员'}, status=status.HTTP_400_BAD_REQUEST)
        activity = activity_data.cash_activity
        data = {}
        data['activity_name'] = activity.name
        data['activity_type'] = activity.activity_type
        data['amount'] = activity_data.amount
        data['available_end_time'] = activity.available_end_time.strftime('%Y年%m月%d日 %H:%M:%S')
        data['state'] = activity_data.state
        if activity_data.state == 1:
            data['desc'] = ''
        elif activity_data.state == 2:
            if activity_data.mchid == '1486198522':
                data['desc'] = '领取成功,请留意微信零钱到账通知'
            else:
                data['desc'] = '领取成功,请留意支付宝余额到账通知'
        elif activity_data.state == 3:
            data['desc'] = f'领取失败,失败原因:{activity_data.return_msg},请重新领取或使用其他方式领取'
        elif activity_data.state == 5:
            if activity_data.mchid == '1486198522':
                data['desc'] = '奖励发放中,请留意微信零钱到账通知'
            else:
                data['desc'] = '奖励发放中,请留意支付宝余额到账通知'
        else:
            data['desc'] = activity_data.return_msg
        data['is_need_auth'] = activity.is_need_auth
        data['activity_description'] = activity.activity_description
        # date_now = datetime.datetime.now()
        # today_time_begin = date_now.strftime('%Y-%m-%d 00:00:00')
        # today_time_end = date_now.strftime('%Y-%m-%d 23:59:59')
        # encouragedraw = CashActivityData.objects.filter(received_time__gte=today_time_begin, received_time__lte=today_time_end, return_msg__contains='已达到今日商户付款额度上限')
        # if encouragedraw:
        #     button = '2'
        # else:
        #     encouragedraw_set = CashActivityData.objects.filter(received_time__gte=today_time_begin, received_time__lte=today_time_end, customeruservice_id=user.id, state=2, mchid='1486198522')
        #     today_amount = Decimal('0')
        #     for encouragedraw in encouragedraw_set:
        #         today_amount += encouragedraw.amount
        #     today_amount += activity_data.amount
        #     if today_amount > Decimal('100'):
        #         button = '2'
        #     else:
        #         button = '3'
        if activity_data.amount < Decimal('1') or activity_data.amount > Decimal('200'):
            button = '2'
        else:
            button = '1'
        data['button'] = button
        return Response(data, status=status.HTTP_200_OK)

    def bank_receive_cash(self, request):
        user = self.request.iser
        identify = self.request.data.get('identify', None)
        login_id = self.request.data.get('login_id', None)
        realname = self.request.data.get('realname', None)
        if not all([identify]):
            return Response({'error': '缺少必传参数', 'status': ''}, status=status.HTTP_400_BAD_REQUEST)
        try:
            activity_data = CashActivityData.objects.get(identify=identify)
        except:
            return Response({'error': '无效红包参数,请联系管理员', 'status': ''}, status=status.HTTP_400_BAD_REQUEST)
        if activity_data.state == 2:
            return Response({'error': '该红包已经被领取', 'status': ''}, status=status.HTTP_400_BAD_REQUEST)
        if activity_data.state not in [1, 3]:
            return Response({'error': '该红包状态有误', 'status': ''}, status=status.HTTP_400_BAD_REQUEST)
        if user.is_mobile != 1:
            return Response({'error': '请先绑定手机号', 'status': '1'}, status=status.HTTP_400_BAD_REQUEST)
        date_now = datetime.datetime.now()
        cash_activity = activity_data.cash_activity
        cash_activity_id = activity_data.cash_activity_id
        if cash_activity.activity_type != 8:
            return Response({'error': '活动类型不支持', 'status': ''}, status=status.HTTP_400_BAD_REQUEST)
        if activity_data.state == 3:
            partner_trade_no = f'{datetime.datetime.now().strftime("%Y%m%d%H%M%S")}{"%09d" % randint(0, 999999999)}'
            activity_data.partner_trade_no = partner_trade_no
        try:
            activity = activity_data.cash_activity
            if activity.is_max_amount_by_customeruser == 1:
                max_amount_by_customeruser__sum = CashActivityData.objects.filter(cash_activity_id=activity.id, customeruservice_id=user.id, state=2).aggregate(Sum('amount'))['amount__sum']
                if max_amount_by_customeruser__sum:
                    max_amount_by_customeruser__sum = Decimal(max_amount_by_customeruser__sum) + activity_data.amount
                    if max_amount_by_customeruser__sum > activity.max_amount_by_customeruser:
                        return Response({'error': f'当前用户领取额度已达上限,剩余可领取金额{activity.max_amount_by_customeruser-max_amount_by_customeruser__sum+activity_data.amount}', 'status': ''}, status=status.HTTP_400_BAD_REQUEST)
            if activity.is_check_identity == 1:
                check_manager = User.objects.filter(mobile=user.mobile, is_active=1)
                if check_manager:
                    return Response({'error': '该活动暂不允许内部员工领取，如有疑问请咨询客服。', 'status': ''}, status=status.HTTP_400_BAD_REQUEST)
        except:
            pass
        if all([login_id, realname]):
            activity_data.state = 5
            activity_data.channel_id = cash_activity.ali_channel_id
            activity_data.save()
            mchid = 'alipay'
            alipay_obj = AlipayOpen()
            trans_amount = str(activity_data.amount)
            order_title = activity_data.desc
            out_biz_no = activity_data.partner_trade_no
            identity = login_id
            if cash_activity.ali_channel_id == 8:
                result = json.loads(alipay_obj.transunitransfer_login_id_jiangxi88(identity, realname, out_biz_no, trans_amount, order_title))
            elif cash_activity.ali_channel_id == 11:
                result = json.loads(alipay_obj.transunitransfer_login_id_jiangxi88_jizhangben(identity, realname, out_biz_no, trans_amount, order_title))
            else:
                result = json.loads(alipay_obj.transunitransfer_login_id(identity, realname, out_biz_no, trans_amount, order_title))
            if result['code'] != '10000':
                activity_data.return_msg = result['sub_msg']
                activity_data.state = 3
                activity_data.received_time = date_now
                activity_data.customeruservice_id = user.id
                activity_data.mchid = mchid
                activity_data.save()
                return Response({'error': f'领取失败,失败原因:{result["err_code_des"]}', 'status': ''}, status=status.HTTP_400_BAD_REQUEST)
            else:
                activity_data.received_time = result['trans_date']
                activity_data.payment_no = result['pay_fund_order_id']
                activity_data.customeruservice_id = user.id
                activity_data.mchid = mchid
                activity_data.state = 2
                activity_data.save()
                while True:
                    activity = CashActivity.objects.get(id=cash_activity_id)
                    origin_distributed_amount = activity.distributed_amount
                    new_distributed_amount = origin_distributed_amount + activity_data.amount
                    result = CashActivity.objects.filter(id=cash_activity_id, distributed_amount=origin_distributed_amount).update(distributed_amount=new_distributed_amount)
                    if result == 0:
                        continue
                    break
                return Response({'success': '领取成功', 'status': ''}, status=status.HTTP_200_OK)
        else:
            mchid = '1486198522'
            appid = settings.CUSTOMER_APP_ID_WYH
            openid = user.wyh_openid
            today_time_begin = date_now.strftime('%Y-%m-%d 00:00:00')
            today_time_end = date_now.strftime('%Y-%m-%d 23:59:59')
            encouragedraw = CashActivityData.objects.filter(received_time__gte=today_time_begin, received_time__lte=today_time_end, return_msg__contains='已达到今日商户付款额度上限')
            if encouragedraw:
                return Response({'error': '微信额度已达到今日上限,请使用支付宝方式领取', 'status': ''}, status=status.HTTP_400_BAD_REQUEST)
            encouragedraw_set = CashActivityData.objects.filter(received_time__gte=today_time_begin, received_time__lte=today_time_end, customeruservice_id=user.id, state=2, mchid='1486198522')
            today_amount = Decimal('0')
            for encouragedraw in encouragedraw_set:
                today_amount += encouragedraw.amount
            today_amount += activity_data.amount
            if today_amount > Decimal('200'):
                return Response({'error': '微信额度已达到今日上限,请使用支付宝方式领取', 'status': ''}, status=status.HTTP_400_BAD_REQUEST)
            activity_data.state = 5
            activity_data.channel_id = cash_activity.wx_channel_id
            activity_data.save()
            params = {
                'mch_appid': appid,
                'mchid': '1486198522',  # 商户号
                'nonce_str': activity_data.nonce_str,
                'partner_trade_no': activity_data.partner_trade_no,
                'openid': openid,
                'check_name': 'NO_CHECK',
                'amount': int(activity_data.amount * 100),
                'desc': activity_data.desc
            }
            data_dict = mmpaymkttransfers(params)
            if data_dict['result_code'] == 'SUCCESS':
                activity_data.state = 2
                activity_data.received_time = data_dict['payment_time']
                activity_data.payment_no = data_dict['payment_no']
                activity_data.customeruservice_id = user.id
                activity_data.mchid = mchid
                activity_data.openid = openid
                activity_data.appid = appid
                activity_data.save()
                while True:
                    activity = CashActivity.objects.get(id=cash_activity_id)
                    origin_distributed_amount = activity.distributed_amount
                    new_distributed_amount = origin_distributed_amount + activity_data.amount
                    result = CashActivity.objects.filter(id=cash_activity_id, distributed_amount=origin_distributed_amount).update(distributed_amount=new_distributed_amount)
                    if result == 0:
                        continue
                    break
                return Response({'success': '领取成功', 'status': ''}, status=status.HTTP_200_OK)
            else:
                activity_data.return_msg = data_dict['err_code_des']
                activity_data.state = 3
                activity_data.received_time = date_now
                activity_data.customeruservice_id = user.id
                activity_data.mchid = mchid
                activity_data.save()
                return Response({'error': f'领取失败,失败原因:{data_dict["err_code_des"]}', 'status': ''}, status=status.HTTP_400_BAD_REQUEST)


class ScoutTheStoreLeaderboardModelViewSet(ModelViewSet):

    serializer_class = ScoutTheStoreLeaderboardModelSerializer

    def get_queryset(self):
        queryset = ScoutTheStoreLeaderboard.objects.all().order_by('-likes')
        return queryset

    def list(self, request, *args, **kwargs):
        data = {}
        queryset = self.filter_queryset(self.get_queryset())
        update_time = queryset.first().update_time.strftime("%m月%d日%H:%M:%S")
        description1 = f'''排行榜每周一、周三、周五更新，排名统计截止至{update_time}'''
        description2 = '''活动时间：即日起至10月7日
活动对象：广东省微邮付商户
活动内容：活动期间，拍摄广东省微邮付商户探店视频，有机会上传至“粤小邮探店”微信视频号，参与探店视频评选，点赞量全省前三名可获ipad大奖！'''
        serializer = self.get_serializer(queryset, many=True)
        data['list'] = serializer.data
        data['description1'] = description1
        data['description2'] = description2
        data['update_time'] = update_time
        return Response(data, status=status.HTTP_200_OK)